uniapp开发商城APP,首页性能优化

使用uniapp开发商城小程序,首页图片加载都是通过后台接口,如果网络不好,首页会出现空白或者加载失败现象,影响用户体验和正常使用。

思路:

1、使用本地缓存存储图片路径。
2、页面加载时,从接口获取新的图片路径,然后再跟本地存储的缓存路径进行对比,如果有变化就替换,反之使用缓存路径(首次加载需要把图片下载到本地)。

代码:

1、对象对比

diffObject(obj1, obj2) {
    
    
	let o1 = obj1 instanceof Object;
	let o2 = obj2 instanceof Object;
	// 判断是不是对象
	if (!o1 || !o2) {
    
    
		return obj1 === obj2;
	}
	if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    
    
		return false;
	}

	for (let o in obj1) {
    
     // 遍历对象 fon in 循环 o 为 对象的属性名  
		let t1 = obj1[o] instanceof Object;
		let t2 = obj2[o] instanceof Object;
		if (t1 && t2) {
    
    
			return this.diffObject(obj1[o], obj2[o]);
		} else if (obj1[o] !== obj2[o]) {
    
    
			// console.log('false')
			return false;
		}
	}
	return true;
},

2、文件下载

fDownLoadFileIos(url, sign) {
    
    
	uni.downloadFile({
    
    
		url: url,
		success: (res) => {
    
    
			if (res.statusCode === 200) {
    
    
				// console.log('下载成功', res);
				// console.log(res.tempFilePath);
				uni.saveFile({
    
    
					tempFilePath: res.tempFilePath,
					success: (res) => {
    
    
						// console.log('保存成功', res);
						const savedFilePath = res.savedFilePath;
						if (sign === 'topBanner') {
    
    
							// console.log('下载。。。。。');
							// console.log(savedFilePath);
							// uni.showModal({
    
    
							// 	title:'下载。。。'
							// })
							this.topBanner = savedFilePath;
							uni.setStorageSync('top_banner_down', savedFilePath)
						}
					}
				});
			}
		},
		fail: (res) => {
    
    
			console.log(res)
			// return filePath
		}
	});
},

3、核心代码

const topBannerUrl = 后台接口图片路径
const topBannerUrlCache = uni.getStorageSync('top_banner_url') // 缓存图片路径
if (uni.getStorageSync('top_banner_down')) {
    
    
	// console.log('有banner.....');
	uni.getSavedFileList({
    
    
		success: (res) => {
    
    
			let hasBanner = false;
			for (let i = 0; i < res.fileList.length; i++) {
    
    
				if (uni.getStorageSync('top_banner_down') === res.fileList[i]
					.filePath) {
    
    
					hasBanner = true;
					break;
				} else {
    
    
					hasBanner = false;
				}
			}
			if (hasBanner) {
    
     // 本地存在banner
				if (topBannerUrl !== topBannerUrlCache) {
    
     // 文件有变化
					// 保存变化的远程URL 
					uni.setStorageSync('top_banner_url', topBannerUrl)
					// 下载图片到手机
					this.fDownLoadFileIos(imgPath, 'topBanner')
				} else {
    
    
					this.topBanner = uni.getStorageSync('top_banner_down')
				}
			} else {
    
    
				// 下载图片到手机
				this.fDownLoadFileIos(imgPath, 'topBanner')
			}
		}
	});

} else {
    
    
	// 下载图片到手机
	this.fDownLoadFileIos(imgPath, 'topBanner')
}

猜你喜欢

转载自blog.csdn.net/weixin_44999830/article/details/127300033
今日推荐