分享一个小程序网络大图加载慢的解决方案
用到的相关api
- getSavedFileList 获取已保存的文件列表;
- getStorageSync 获取本地缓存;
- downloadFile 下载网络图片;
- saveFile 保存文件到本地;
- setStorage 将数据储存到小程序本地缓存;
整体思路如下:
先获取已保存的本地文件,如果从来没有保存过,就先下载网络图片并保存到本地,同时将文件路劲缓存到小程序,等下次需要的时候直接拿文件路径去匹配本地文件的路径,实现图片秒开的效果;
遗留问题:需要先加载再缓存,初次加载还是会加载比较慢?
代码实现
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.filePathreturn}}// 首次加载等待uni.showLoading({title: '加载中...'})uni.downloadFile({url: '要加载的网络文件地址',success: ({ tempFilePath })=> {this.imagePath = tempFilePathuni.saveFile({tempFilePath,success: ({ savedFilePath })=> {this.imagePath = savedFilePath},complete: ()=> {uni.hideLoading()uni.setStorage({key: 'cacheImgKey',data: this.imagePath})}})}})}
})
解决遗留的问题,即 初次加载也能达到秒开的效果,如何处理?
解决方案:可在前置页面预先加载并缓存文件
前置页面判断本地缓存,如果没有可先下载文件保存
const cacheImgKey = uni.getStorageSync('cacheImgKey')
if(!cacheImgKey) {uni.downloadFile({url: '要加载的网络文件地址',success: ({ tempFilePath })=> {uni.saveFile({tempFilePath,success: ({ savedFilePath })=> {uni.setStorage({key: 'cacheImgKey',data: savedFilePath})}})}})
}
END.