介绍图片懒加载
什么是懒加载?
- 懒加载突出一个“懒”字,懒就是拖延迟的意思,所以“懒加载”说白了就是延迟加载,比如我们加载一个页面,这个页面很长很长,长到我们的浏览器可视区域装不下,那么懒加载就是优先加载可视区域的内容,其他部分等进入了可视区域在加载。
为什么要懒加载?
-
懒加载是一种网页性能优化的方式,它能极大的提升用户体验。就比如说图片,图片一直是影响网页性能的主要元凶,现在一张图片超过几兆已经是很经常的事了。如果每次进入页面就请求所有的图片资源,那么可能等图片加载出来用户也早就走了。所以,我们需要懒加载,进入页面的时候,只请求可视区域的图片资源。
-
总结出来就两个点:
1.全部加载的话会影响用户体验
2.浪费用户的流量,有些用户并不像全部看完,全部加载会耗费大量流量。
懒加载的实现原理?
-
由于网页中占用资源较多的一般是图片,所以我们一般实施懒加载都是对图片资源而言的,所以这里的实现原理主要是针对图片。
-
大家都知道,一张图片就是一个
<img>
标签,而图片的来源主要是src属性。浏览器是否发起亲求就是根据是否有src属性决定的。 -
既然这样,那么我们就要对
<img>
标签的src属性下手了,在没进入可视区域的时候,我们先不给这个<img>
标签赋src属性,这样岂不是浏览器就不会发送请求了。
使用vue-lazyload完成图片懒加载
- 介绍了图片懒加载,我们就要介绍在vue中使用vue-lazyload完成图片的懒加载。
- 首先,我们参考github上vue-lazylaod的资料。
- 然后在项目中使用图片的vue-lazyload。
通过npm安装
npm i vue-lazyload -S
使用
- main.js文件:
import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
// or with options
const loadimage = require('./assets/loading.gif')
const errorimage = require('./assets/error.gif')
Vue.use(VueLazyload, {
preLoad: 1.3,
error: errorimage,
loading: loadimage,
attempt: 1
})
new Vue({
el: 'body',
components: {
App
}
})
- 在入口文件添加后,在组件任何地方都可以直接使用把 img 里的:src -> v-lazy
<div class="pic">
<a href="#"><img :src="'/static/img/' + item.productImage" alt=""></a>
</div>
把之前项目中img 标签里面的 :src 属性 改成 v-lazy
<div class="pic">
<a href="#"><img v-lazy="'/static/img/' + item.productImage" alt=""></a>
</div>
- 参数选项:
key | description | default | options |
---|---|---|---|
preLoad | 预压高度比例 | 1.3 | Number |
error | src of the image upon load fail | 'data-src' | String |
loading | src of the image while loading | 'data-src' | String |
attempt | 尝试计数 | 3 | Number |
listenEvents | 想要监听的事件 | ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend', 'touchmove'] | Desired Listen Events |
adapter | 动态修改元素属性 | { } | Element Adapter |
filter | 图片监听或过滤器 | { } | Image listener filter |
lazyComponent | lazyload 组件 | false | Lazy Component |
dispatchEvent | 触发dom事件 | false | Boolean |
throttleWait | throttle wait | 200 | Number |
observer | use IntersectionObserver | false | Boolean |
observerOptions | IntersectionObserver options | { rootMargin: ‘0px’, threshold: 0.1 } | IntersectionObserver |
silent | do not print debug info | true | Boolean |
想要监听的事件
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1,
// the default is ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend']
listenEvents: [ 'scroll' ]
})