2

优化-图片懒加载_前端开发的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15473285/5814698
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

优化-图片懒加载

精选 原创

晨曦前端 2022-11-01 18:21:39 博主文章分类:vue ©著作权

文章标签 自定义指令 懒加载 加载 文章分类 JavaScript 前端开发 阅读数174

我们开发商城项目的时候,商品图片会有很多

如果在进入页面一下子就加载很多图片资源的话,会导致进入页面会很慢

我们今天说到的图片懒加载,是一个优化层面的
主要会有哪些优点呢?

比如:加载页面会快一些,包体积会小一些

网络层面的话就是减少了http请求

我们都知道,在浏览器打开的瞬间,同一时间最多并行6-8个请求

如果说图片请求比较多的话,就有可能和其它请求发生竞争关系,造成网络堵塞,会影响其它比较重要的网络请求

实现图片懒加载,主要使用vue3的自定义指令,进行按需加载


import defaltImg from '@/assets/images/200.png'
// 引入监听是否进入视口
import { useIntersectionObserver } from '@vueuse/core'

export default{
  install(app){
  // 自定义指令
    app.directive('imglazy',{
      mounted(el,binding){
        // el:  dom对象
        // binding:binding.value可以拿到图片的url地址
        const { stop } = useIntersectionObserver(
          //监听目标元素
          el,
          ([{ isIntersecting }], observerElement) => {
            if(isIntersecting){
              // 当图片加载失败的时候就用默认的图片代替
              el.onerror=()=>{
                el.src = defaltImg
              }
              el.src = binding.value
              stop()
            }
          },
          // 刚进入视口区域就立刻执行回调 0 - 1 
          { threshold: 0 }
        )
      }
    })
  }
}

最后我们需要在全局入口文件中将其注册为插件即可

import defineDirective from '@/directives'
createApp(App).use(store).use(router).use(componentPlugin).use(directivePlugin).mount('#app')

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK