小程序網絡圖片讀取:web
爲了儘可能減小上面兩個問題,因此對已讀的圖片進行緩存處理,減小屢次訪問沒必要要的流量消耗。小程序
文件主要分爲兩大類:緩存
其中本地文件又分爲三種:網絡
而咱們要使用的文件緩存方式就是 本地臨時文件 。異步
圖片緩存流程:post
wx.downloadFile(Object object)
下載到本地,成爲本地臨時文件。FileSystemManager.accessSync(string path)
判斷文件存在,則讀取本地地址;不存在,刪除該映射。1~2M
作其餘代碼備用,而文件異步保存,自己會致使有好多文件沒法檢測到,若是經過循環去判斷最近時間,太耗費性能,還不如進入小程序時,直接清空,從頭開始。小程序自己是輕量級的,一段時間清空一次便可。const fileSystem = wx.getFileSystemManager() const getStorageImage = (web_image) => { let webImages = wx.getStorageSync('webImages') || [] let webImage = webImages.find(y => y.web_path === web_image) if (webImage) { try { fileSystem.accessSync(webImage.local_path) return webImage.local_path } catch(e) { let webImageIdx = webImages.findIndex(y => y.web_path === web_image) webImages.splice(webImageIdx, 1) wx.setStorageSync('webImages', webImages) } } else { wx.downloadFile({ url: web_image, success (res) { if (res.statusCode === 200) { let filePath = res.tempFilePath let webImageStorage = wx.getStorageSync('webImages') || [] let storage = { web_path: web_image, local_path: filePath, last_time: Date.parse(new Date()), } webImageStorage.push(storage) wx.setStorageSync('webImages', webImageStorage) } } }) } return web_image } module.exports = { getStorageImage }
本文參照博客性能
https://juejin.im/post/5b42d3ede51d4519277b6ce3
(幽蟄 寫於 2020.06.10)url