背景
h5页面,很多时候存在大量的图片、动画,这些都需要下载大量的静态资源,如果我们直接打开页面,会发现部分图片正在加载或者还未下载的现象,严重影响体验效果。
为了解决这个问题,我们需要进行图片预加载
的操作。
什么是图片预加载?
简单来说,图片预加载就是在页面渲染前把所有的图片、GIF等静态资源全部下载完毕,使得页面渲染后直接打开缓存的图片资源,从而减少卡顿的问题,优化用户体验。
那么如何在h5中实现图片预加载呢?
具体实现
<template>
<view v-if="loaded">
已加载{{percent}}
</view>
<view v-else>
//具体页面的内容
</view>
</template>
<script>
export default {
data() {
return {
loaded: false,
count: 0,
urls: [
'/building/static/云[email protected]',
'/building/static/云[email protected]',
'/building/static/云[email protected]',
'/building/static/[email protected]',
'/building/static/背景@3x.jpg',
'/building/static/大坝@3x.png',
'/building/static/道路@3x.png',
'/building/static/道路-里层@3x.png',
'/building/static/卡车@3x.png',
'/building/static/中国风线条[email protected]',
'/building/static/中国风线条[email protected]',
'/building/static/中国风线条[email protected]',
'/building/static/音乐开.png',
'/building/static/楼@3x.png',
'/building/static/挖掘机@3x.png',
'/building/static/人@3x.png',
'/building/static/人-手臂@3x.png',
'/building/static/[email protected]',
'/building/static/塔吊-主体@3x.png',
'/building/static/塔吊-线@3x.png',
'/building/static/塔吊-钩子@3x.png',
'/building/static/信纸@3x.png',
'/building/static/信封盖@3x.png',
'/building/static/信封顶@3x.png',
'/building/static/信封背景@3x.png',
'/building/static/信封完整@3x.png',
'/building/static/边框[email protected]',
'/building/static/边框[email protected]',
'/building/static/留言板@3x.png',
'/building/static/[email protected]',
'/building/static/[email protected]',
'/building/static/挖掘机动画.gif',
'/building/static/分享提示.png',
'/building/static/qrcode.png',
],
percent: '',
loaded:false,
}
},
mounted() {
this.preLoad(); //预加载图片
},
watch: {
count: function(val, old) {
if (val === this.urls.length) { // 图片全部加载完成后跳转页面
console.log('loaded')
this.loaded = true;
}
},
},
methods:{
preLoad() { //预加载图片
for (let url of this.urls) {
let image = new Image()
image.src = url
console.log(url)
image.onload = () => {//加载完毕事件
this.count++
// 计算图片加载的百分数,绑定到percent变量
let percentNum = Math.floor(this.count / this.urls.length * 100)
this.percent = `${percentNum}%`
}
}
},
}
}
</script>
解析
- 利用image的src属性,下载图片,下载完成触发onload事件
- 用count统计已下载的图片数量,在加载页面显示加载进度percent
- 用loaded属性,加载完毕切换页面
结语
图片做完预加载后,如果依然出现显示卡顿、滚动显示的现象,我们就要从以下几方面继续做优化:
- 图片压缩,尽可能压缩图片的体积,能有效提高显示的效果
- 网速、带宽优化