npm install 参数区别

图片懒加载就是对于有很多图片的页面,为了提高页面加载速度,只加载可视区域内的图片,可视区域外的等到滚动到可视区域后再去加载

这个功能一些 UI 框架都有自带的,如果没有呢?

推荐一个第三方插件 vue-lazyload

npm i vue-lazyload -S

// main.js
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)

// 接着就可以在页面中使用 v-lazy 懒加载图片了
<img v-lazy="/static/images/1.png">

或者自己造轮子,手动封装一个自定义指令,这里封装好了一个兼容各浏览器的版本的,主要是判断浏览器支不支持 IntersectionObserver API,支持就用它实现懒加载,不支持就用监听 scroll 事件+节流的方式实现

const LazyLoad = { 
// install方法 
install(Vue, options) {  
 const defaultSrc = options.default 
 Vue.directive('lazy', {  
  bind(el, binding) {   
   LazyLoad.init(el, binding.value, defaultSrc) 
 },   
  inserted(el) {     
   if (IntersectionObserver) {    
    LazyLoad.observe(el)     
  } else {      
    LazyLoad.listenerScroll(el)    
  }  
 }, 
})
}, 
// 初始化 
init(el, val, def) { 
 el.setAttribute('data-src', val)  
 el.setAttribute('src', def)
}, 
// 利用IntersectionObserver监听el
observe(el) {  
 var io = new IntersectionObserver((entries) => {  
  const realSrc = el.dataset.src    
 if (entries[0].isIntersecting) {   
  if (realSrc) {      
   el.src = realSrc       
   el.removeAttribute('data-src')    
  }   
 } 
}) 
 io.observe(el)
}, 
// 监听scroll事件
listenerScroll(el) {  
 const handler =
LazyLoad.throttle(LazyLoad.load, 300) 
 LazyLoad.load(el)  
 window.addEventListener('scroll', () => {   
  handler(el) 
 })
}, 
// 加载真实图片 
load(el) {  
 const windowHeight =
document.documentElement.clientHeight
 const elTop = el.getBoundingClientRect().top  
 const elBtm = 
el.getBoundingClientRect().bottom 
 const realSrc = el.dataset.src  
 if (elTop - windowHeight < 0 && elBtm > 0) {  
  if (realSrc) {     
   el.src = realSrc    
   el.removeAttribute('data-src')  
  } 
 }
}, 
// 节流 
throttle(fn, delay) {  
 let timer  
 let prevTime  
 return function (...args) {   
  const currTime = Date.now() 
  const context = this    
  if (!prevTime) prevTime = currTime  
  clearTimeout(timer)   
  
  if (currTime - prevTime > delay) {     
   prevTime = currTime      
   fn.apply(context, args)    
   clearTimeout(timer)      
   return   
 }  

 timer = setTimeout(function () {   
  prevTime = Date.now()  
  timer = null   
  fn.apply(context, args)   
}, delay) 
}
},
}
export default LazyLoad

使用上是这样的,用 v-LazyLoad 代替 src

<img v-LazyLoad="xxx.jpg" />

猜你喜欢

转载自blog.csdn.net/jieweiwujie/article/details/122719329