小程序网络大文件缓存方案

分享一个小程序网络大图加载慢的解决方案

用到的相关api

  1. getSavedFileList 获取已保存的文件列表;
  2. getStorageSync 获取本地缓存;
  3. downloadFile 下载网络图片;
  4. saveFile 保存文件到本地;
  5. setStorage 将数据储存到小程序本地缓存;

整体思路如下:

先获取已保存的本地文件,如果从来没有保存过,就先下载网络图片并保存到本地,同时将文件路劲缓存到小程序,等下次需要的时候直接拿文件路径去匹配本地文件的路径,实现图片秒开的效果;

遗留问题:需要先加载再缓存,初次加载还是会加载比较慢?

代码实现

javascript 复制代码
uni.getSavedFileList({
	complete: (res)=> {
		console.log(res)

		const cacheImgKey = uni.getStorageSync('cacheImgKey')
		if(res.fileList.length) {
			const data = res.fileList.find(item=> item.filePath == cacheImgKey)
			if(data) {
				this.imagePath = data.filePath
				return
			}
		}

		// 首次加载等待
		uni.showLoading({
			title: '加载中...'
		})
		uni.downloadFile({
			url: '要加载的网络文件地址',
			success: ({ tempFilePath })=> {
				this.imagePath = tempFilePath
				uni.saveFile({
					tempFilePath,
					success: ({ savedFilePath })=> {
						this.imagePath = savedFilePath
					},
					complete: ()=> {
						uni.hideLoading()
						uni.setStorage({
							key: 'cacheImgKey',
							data: this.imagePath
						})
					}
				})
			}
		})
	}
})

解决遗留的问题,即 初次加载也能达到秒开的效果,如何处理?

解决方案:可在前置页面预先加载并缓存文件

前置页面判断本地缓存,如果没有可先下载文件保存

javascript 复制代码
const cacheImgKey = uni.getStorageSync('cacheImgKey')
if(!cacheImgKey) {
	uni.downloadFile({
		url: '要加载的网络文件地址',
		success: ({ tempFilePath })=> {
			uni.saveFile({
				tempFilePath,
				success: ({ savedFilePath })=> {
					uni.setStorage({
						key: 'cacheImgKey',
						data: savedFilePath
					})
				}
			})
		}
	})
}

END.

如果觉得有用随手点个赞吧,谢谢

关注我,不定时分享技术干货~

相关推荐
only-qi19 小时前
Redis如何应对 Redis 大 Key 问题
数据库·redis·缓存
天生励志1231 天前
Redis 安装部署
数据库·redis·缓存
武帝为此1 天前
【Redis 数据库介绍】
数据库·redis·缓存
铁锚1 天前
Redis中KEYS命令的潜在风险与遍历建议
数据库·redis·缓存
程序员果子1 天前
零拷贝:程序性能加速的终极奥秘
linux·运维·nginx·macos·缓存·centos
可爱の小公举1 天前
Redis技术体系全面解析
数据库·redis·缓存
Mxsoft6191 天前
接触电阻监测误报,多物理场特征融合救场!
缓存
Geoking.1 天前
Redis 中 ziplist 与 quicklist 解析与对比
数据库·redis·缓存
第二只羽毛1 天前
C++高性能内存池
开发语言·c++·缓存·性能优化
#微爱帮#1 天前
微爱帮监狱寄信写信小程序OCR图片识别技术的选型、优化和实际应用。
小程序