ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

前端使用cache storage实现远程图片缓存

2026/8/4 8:57:58 拓冰建站 浏览量
前端使用cache storage实现远程图片缓存

Cache Storage 的主要特点和用途

  1. 缓存网络资源:可以将经常访问的网络资源缓存到 Cache Storage 中,以提高网页加载速度,减少网络请求。
  2. 离线访问:当用户处于离线状态时,可以使用 Cache Storage 中的缓存资源来加载网页内容,提供更好的离线访问体验。
  3. 优先级控制:可以通过设置缓存的优先级,确保重要资源优先缓存,而不会占用过多的存储空间。

效果

网页中的图片首次加载时会将图片blob文件存储到cache,网页刷新图片优先从cache缓存中读取,不会再次从服务器请求
作者:__sgf__
链接:https://www.nowcoder.com/discuss/516278915950735360
来源:牛客网
[^1]: [mermaid语法说明](https://mermaidjs.github.io/)

<template><div><img :src="src" :style="style"/></div>
</template>
<script>
import req from '@/request.js';
export default {name: 'eip-img',props: ['isDisplay', 'imgSrc', 'fileJson', 'imgHeight', 'imgWidth', 'urlSetting'],data() {return {src: '',style: {},};},computed: {},created() {this.testCache()if (this.imgHeight > 0 && this.imgWidth > 0) {this.style = {height: this.imgHeight + 'px',width: this.imgWidth + 'px',};}},methods: {async testCache(){let _this = this;if (this.isDisplay) {if (this.fileJson) {var json = JSON.parse(this.fileJson);let id = json[0].id;var cacheName = 'eipimg'  // 定义cache名称var path = window.context.portal + '/file/onlinePreviewController/v1/getFileById_' + id  // 定义路径var cachesMatch = await caches.match(path) // 匹配当前路径var cachesLocal = await caches.has(cacheName)//如果当前已有数据则直接获取缓存的数据if(cachesMatch && cachesLocal){caches.match(path).then(res => {return res.text()}).then(res => {// console.log("获取cache数据: ", res)_this.src = res})}else{// 如果没有则获取远程数据req.get(path, 'arraybuffer').then(response => {var reader = new window.FileReader();reader.readAsDataURL(new Blob([response.data])); reader.onloadend = function() {_this.src = reader.result// 将请求的数据保存在caches中caches.open(cacheName).then(cache => {cache.put(path, new Response(reader.result, { status: 200 }))})}});}}} else {this.src = this.imgSrc;}}}
};
</script>
<style lang="stylus" scoped>
div[aria-invalid='true'] >>> .el-input__inner, div[aria-invalid='true'] >>> .el-input__inner:focus {border-color: #f56c6c;
}
</style>

调用

<eip-img  isDisplay="true" imgSrc="" :imgHeight='60' :imgWidth='60' :fileJson='`[{"id": "${item.id}"}]`' />