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

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

用到的相关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.

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

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

相关推荐
皮卡祺q3 分钟前
【redis1】基本指令,五大数据类型,存储优化,使用场景】
数据库·redis·缓存
Mr. zhihao21 分钟前
Redis Bitmap:BitCount、bitTop的使用业务场景
数据库·redis·缓存
biwenyunnet42 分钟前
【99做小程序只认餐宝盈】连锁餐饮小程序怎么做:从系统架构、技术选型到表结构与接口设计的完整实践
小程序·系统架构
闪电悠米1 小时前
黑马点评-分布式锁-02_simple_redis_lock_setnx
java·数据库·spring boot·redis·分布式·缓存·wpf
闪电悠米2 小时前
黑马点评-分布式锁-03_lua_atomic_unlock
java·数据库·分布式·缓存·oracle·wpf·lua
27669582922 小时前
拼多多m端/小程序 encrypt_info
java·小程序·apache·encrypt_info·encrypt_info解密·拼多多小程序·拼多多m端
小马爱打代码2 小时前
SpringBoot + 本地缓存 + 布隆过滤器:防止恶意 ID 查询打穿数据库
数据库·spring boot·缓存
克里斯蒂亚诺更新3 小时前
微信小程序体验版可以获取当前位置但是正式版不可以-办法解决
微信小程序·小程序
资深前端之路3 小时前
微信小程序节点最大限制为5000个
微信小程序·小程序
逻极3 小时前
Redis 从入门到精通:缓存设计与实战
数据结构·redis·缓存·哨兵集群