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

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

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

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

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

相关推荐
2501_915921432 小时前
iOS 26 CPU 使用率监控策略 多工具协同构建性能探索体系
android·ios·小程序·https·uni-app·iphone·webview
狂团商城小师妹2 小时前
JAVA国际版同城打车源码同城服务线下结账系统源码适配PAD支持Android+IOS+H5
android·java·ios·小程序·交友
游戏开发爱好者82 小时前
iOS 应用逆向对抗手段,多工具组合实战(iOS 逆向防护/IPA 混淆/无源码加固/Ipa Guard CLI 实操)
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张3 小时前
iOS 文件管理与导出实战,多工具协同打造高效数据访问与调试体系
android·macos·ios·小程序·uni-app·cocoa·iphone
白露与泡影5 小时前
Redis:我是如何与客户端进行通信的
数据库·redis·缓存
小生凡一13 小时前
redis 大key、热key优化技巧|空间存储优化|调优技巧(一)
数据库·redis·缓存
小马哥编程13 小时前
【软考架构】案例分析-对比MySQL查询缓存与Memcached
java·数据库·mysql·缓存·架构·memcached
2301_8029399015 小时前
从零开始学习Redis(五):多级缓存
redis·学习·缓存
JavaEdge.15 小时前
榨干 CPU 性能:通过绑核将 Redis 尾延迟减半!
数据库·redis·缓存
一个儒雅随和的男子15 小时前
Redis大Key调优指针
数据库·redis·缓存