为了减少网络请求,提升页面加速速度,可以使用懒加载来做优化。
<img src="https://shirtoid.com/wp-content/uploads/2009/09/loading.jpg" alt="">
<script>
console.log('开始加载图片', new Date().getTime());
// 分页请求
// 触发条件再请求
// 监听图片加载完毕后触发
var img = new Image();
img.src = 'https://shirtoid.com/wp-content/uploads/2009/09/loading.jpg';
img.onload = function () {
console.log('图片加载完毕...', new Date().getTime());
document.querySelector('img').src = 'https://tse1-mm.cn.bing.net/th/id/OIP-
C.iP738K4uYOe1mViOLprM2QHaE8?pid=ImgDet&rs=1';
}
console.log('代码执行完毕', new Date().getTime());
</script>
还可以通过js提供的IntersectionObserver构造函数来监听实现懒加载,它的参数是一个回调函数,其默认参数有个isIntersecting属性,可以通过这个属性来判断容器元素是否在可视区域内;它还有一些方法,IntersectionObserver.observe()开始监听一个目标元素,IntersectionObserver.unobserve()停止监听特定目标元素。IntersectionObserver.unobserve()IntersectionObserver.observe()
IntersectionObserver - Web API 接口参考 | MDN
<template>
<div class="container" v-for="(item, index) in newList" :key="index">
<div class="imgbox">
<img v-img-lazy="item" alt="">
</div>
</div>
</template>
<script setup>
// 获取图片资源
const imgList = import.meta.glob('@/assets/images/*.*', { eager: true })
// 转为数组
let newList = Object.values(imgList).map(el => el.default)
const vImgLazy = async (el, binding) => {
const def = await import('@/assets/logo.svg')
el.src = def.default
const ob = new IntersectionObserver(entries => {
// console.log(entries);
if (entries[0].isIntersecting) {
setTimeout(() => {
el.src = binding.value
// 停止监听
ob.unobserve(el)
}, 1000)
}
})
ob.observe(el)
}
</script>