这是我参与8月更文挑战的第16天,活动详情查看:8月更文挑战
!
定义
延迟加载图片或符合某些条件时才加载某些图片
原理
在图片没有进入可视区域时,先不给的src赋值,这样浏览器就不会发送请求了,等到图片进入可视区域再给src赋值
目的
减少不必要的访问数据库或延迟访问数据库的次数,因为每次访问数据库都是比较耗时的即只有真正使用该对象的数据时才会创建。懒加载的主要目的是作为服务器前端的优化,减少请求数或延迟请求数
懒加载的优点
- 可以减少首页首次加载的数量,减少服务器的压力
- 当网络请求比较慢的时候, 提前给这张图片添加一个像素比较低的占位图片,提高用户体验
运用场景
如果一个页面需要好多图片需要加载,页面会变得非常的卡顿,此时如果只是可视区域的图片加载,其他的图片可以暂时有一个占位 loading 图,等滚动它们到可视区域时再去请求真实图片并且替换就好了
vue中如何使用
使用vue-lazyload 插件
(1)安装插件
npm install vue-lazyload --save-dev
(2)在入口文件 man.js 中引入并使用
import VueLazyload from 'vue-lazyload'
然后再 vue 中直接使用
Vue.use(VueLazyload)
或者添加自定义选项
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',//图片路径错误时加载图片
loading: 'dist/loading.gif',//预加载图片
attempt: 1
})
下表为vue-lazyload详细api:
| key | description | default | options |
|---|---|---|---|
preLoad | proportion of pre-loading height(预加载高度比例) | 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 | attempts count(尝试加载图片数量) | 3 | Number |
listenEvents | events that you want vue listen for(想要监听的vue事件)默认['scroll']可以省略,当插件跟页面中的动画或过渡等事件有冲突是,可以尝试其他选项 | ['scroll'(默认),``'wheel',``'mousewheel',``'resize',``'animationend',``'transitionend',``'touchmove'] | Desired Listen Events |
adapter | dynamically modify the attribute of element(动态修改元素属性) | { } | Element Adapter |
filter | the image's listener filter(动态修改图片地址路径) | { } | Image listener filter |
lazyComponent | lazyload component | false | Lazy Component |
dispatchEvent | trigger the dom event | false | Boolean |
throttleWait | throttle wait | 200 | Number |
observer | use IntersectionObserver | false | Boolean |
observerOptions | IntersectionObserver options | { rootMargin: '0px', threshold: 0.1 } | IntersectionObserver |
(3)在 vue 文件中将 img 标签的 src 属性直接改为 v-lazy ,从而将图片显示方式更改为懒加载显示:
<img v-lazy="/static/img/1.png">