利用图片懒加载---优化网页性能
当用户进入网页,所有图片都进行加载,但是用户并不需要访问所有图片时候,此时便造成了资源浪费
解决流程
用户进入网站=>检测用户是否访问=>进行图片加载=>开发中进行绑定
检测用户是否访问
通过vueuse实用函数合集API,我们可以找到 useIntersectionObserver(vueuse.nodejs.cn/core/useInt…)*,它可以监听用户是否访问到指定的区域,然后进行反馈。
下面是 useIntersectionObserver的用法
<script setup>
import { useIntersectionObserver } from '@vueuse/core' //进行方法导入
import { ref } from 'vue'
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target, //target是你需要检测的元素
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
//isTntersecting是检测该元素是否出现在视图=>如果出现返回"True",否则"false"
)
</script>
<template>
<div ref="target">
<h1>Hello world</h1>
</div>
</template>
通过上述例子的分析,你将可以知道,它拥有访问对象target,判断是否浏览的isIntersecting 以及,停止监听的stop(),掌握这三种,你将可以简单的监听用户是否访问到指定的元素。
下面是 useIntersectionObserver的例子
<script setup lang="ts">
import { vIntersectionObserver } from '@vueuse/components'
import { ref } from 'vue'
const root = ref(null)
const isVisible = ref(false)
function onIntersectionObserver([{ isIntersecting }]: IntersectionObserverEntry[]) {
isVisible.value = isIntersecting
}
</script>
<template>
<div>
<p>
Scroll me down!
</p>
<div v-intersection-observer="onIntersectionObserver">
<p>Hello world!</p>
</div>
</div>
<!-- with options -->
<div ref="root">
<p>
Scroll me down!
</p>
<div v-intersection-observer="[onIntersectionObserver, { root }]">
<p>Hello world!</p>
</div>
</div>
</template>
进行图片懒加载
到这一步,你已经可以检测用户是否访问到图片区域了,剩下的就是如何进行图片加载了
图片加载我们将利用vue的自定义指令
我们命名一个名为lazyPlugin的插件,并将其导出。
//lazyPlugin.vue
import { useIntersectionObserver } from '@vueuse/core'
export const lazyPlugin={
install(app){
//自定义全局指令
//el是目标元素,bindling类似于:src="" =右边的赋值
app.directive('img-lazy',{
mounted(el,bindling){
const {stop}=useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if(isIntersecting){
el.src=bindling.value
stop()//加载完后停止监听=>性能优化
}
},
)
}
})
}
}
提醒: 在代码中,我们可以发现stop()。因为useIntersectionObserver会一直进行监听,所以无论加载是否,只要访问一次指定区域就会触发相对于的事件,所以避免性能浪费,我们在第一次加载结束时候,就可以停止它的监听,优化性能
在主文件中进行挂载
//main.js
import {lazyPlugin} from '@/directives/index'
app.use(lazyPlugin)
在具体开发中进行绑定
//xxx.vue
<img v-img-lazy="item.picture" alt="">
那么到这一步,你将拥有了图片懒加载的功能,成功让浏览器性能得到了优化!!!