vue-lazyload 圖片懶加載- 實踐與源碼
「~實踐與源碼 ~」
* 學習進階方式 💪
- 基礎(chǔ)知識要夯實;
- 原理源碼要深入;
- 深度廣度要擴展;
vue-lazyload 解決了什么問題?(項目常用)
可以想象一個網(wǎng)頁打開有成百上千的圖片需要加載,頁面會變得非常的卡頓,此時如果只是可視區(qū)域的圖片加載,其他的圖片可以暫時有一個占位loading圖,等滾動它們到可視區(qū)域時再去請求真實圖片并且替換就好了。很好,vue-lazyload插件就是解決此類問題的。
vue-lazyload 圖片懶加載- 實踐
一、安裝插件
vue-lazyload官網(wǎng)npm配置地址(重要)
https://www.npmjs.com/package/vue-lazyload
- npm i vue-lazyload --save
二、配置插件
在main.js 文件中 引入 vue-lazyload 的插件。 (全局)
1、最外層static目錄下的圖片引用
- import VueLazyLoad from 'vue-lazyload';
- // 最外層static目錄下的圖片引用
- Vue.use(VueLazyLoad, {
- error: '/static/images/defaultAvatar.png', // 此處是圖片加載失敗時候 顯示的圖片
- loading: '/static/images/defaultAvatar.png', // 此處是圖片加載中 顯示的圖片
- attempt: 1, // 加載一屏圖片
- preLoad: 1, // 失敗嘗試次數(shù)
- });
2、src下的assets目錄下的圖片
- import VueLazyLoad from 'vue-lazyload';
- // src下的assets目錄下的圖片
- Vue.use(VueLazyLoad, {
- error: require('common/assets/defaultAvatar.png'), // 此處是圖片加載失敗時候 顯示的圖片
- loading: require('common/assets/defaultAvatar.png'), // 此處是圖片加載中 顯示的圖片
- attempt: 1, // 加載一屏圖片
- preLoad: 1, // 失敗嘗試次數(shù)
- });
*項目使用遇到問題,說明:
import VueLazyLoad from 'vue-lazyload';
報錯:Absolute imports should come before relative imports.
原因:主要是引入文件的位置問題。
三、使用插件
只需要在動態(tài)請求img 路徑 把原本的 :scr="url", 替換為 v-lazy="url" 接下來,再去看看效果實例。
- <img v-lazy="talent.cover_url" :key="talent.cover_url" class="picsrc" >
說明:
選項卡模式的圖片列表,每次點擊切換時候,會請求不同數(shù)量,不同的圖片內(nèi)容。然而發(fā)現(xiàn) 列表中的前幾個圖片,無論怎么來回切換,每次都顯示最開始的圖片。
這個時候 解決辦法是 在img 里面 加上 :key="url" 就可以解決這個bug;
四、項目需求:不同模塊選擇不同的圖片 (局部)
vue-lazyload插件如何做不同模塊選擇不同的loading圖片(通過樣式進行設(shè)置)
- import VueLazyLoad from 'vue-lazyload';
- // 最外層static目錄下的圖片引用
- Vue.use(VueLazyLoad, {
- // error: '/static/images/defaultAvatar.png', // 此處是圖片加載失敗時候 顯示的圖片
- // loading: '/static/images/defaultAvatar.png', // 此處是圖片加載中 顯示的圖片
- // attempt: 1, // 加載一屏圖片
- // preLoad: 1, // 失敗嘗試次數(shù)
- });
- // 圖片加載中、加載結(jié)束、或者加載錯誤三種狀態(tài)
- <style>
- .yourclass[lazy=loading] {
- /*your style here*/
- }
- .yourclass[lazy=error] {
- /*your style here*/
- }
- .yourclass[lazy=loaded] {
- /*your style here*/
- }
- </style>
注意:全局與局部是單獨設(shè)置的,全局的優(yōu)先級高。
五、構(gòu)造函數(shù)選項

vue-lazyload 圖片懶加載- 源碼
一、原理剖析
lazyload的主要流程的流程圖

原理簡述:
1)vue-lazyload是通過指令的方式實現(xiàn)的,定義的指令是v-lazy指令;
2)指令被bind時會創(chuàng)建一個listener,并將其添加到listener queue里面, 并且搜索target dom節(jié)點,為其注冊dom事件(如scroll事件);
3)上面的dom事件回調(diào)中,會遍歷 listener queue里的listener,判斷此listener綁定的dom是否處于頁面中perload的位置,如果處于則加載異步加載當前圖片的資源;
4)同時listener會在當前圖片加載的過程的loading,loaded,error三種狀態(tài)觸發(fā)當前dom渲染的函數(shù),分別渲染三種狀態(tài)下dom的內(nèi)容;
二、源碼解析:
1、在組件install安裝時,調(diào)用LazyClass返回了一個class對象,然后創(chuàng)建了一個class實例。
2、其核心是lazyLoadHandler()函數(shù),是經(jīng)過節(jié)流函數(shù)處理的圖片加載的入口函數(shù)。
- this.lazyLoadHandler = throttle(() => {
- let catIn = false
- this.ListenerQueue.forEach(listener => {
- if (listener.state.loaded) return
- catIn = listener.checkInView()
- catIn && listener.load()
- })
- }, 200)
- checkInView () {
- this.getRect() // 調(diào)用dom的getBoundingClientRect()
- return (this.rect.top < window.innerHeight * this.options.preLoad && this.rect.bottom > this.options.preLoadTop) &&
- (this.rect.left < window.innerWidth * this.options.preLoad && this.rect.right > 0)
- // 判斷dom的頂部是否到了preload的位置,判斷dom的底部是否到達了preload的位置,X軸同理。
- }
3、主要操作:找到對應(yīng)的target(用于注冊dom事件的dom節(jié)點;比如:頁面滾動的dom節(jié)點),為其注冊dom事件;為當前dom創(chuàng)建Listenr并添加到listener queue中。最后用lazyLoadHandler()函數(shù),加載圖片。
4、當滿足條件,調(diào)用load()函數(shù)異步加載圖片。
- load () {
- // 如果當前嘗試加載圖片的次數(shù)大于指定的次數(shù), 并且當前狀態(tài)還是錯誤的, 停止加載動作
- if ((this.attempt > this.options.attempt - 1) && this.state.error) {
- if (!this.options.silent) console.log('error end')
- return
- }
- if (this.state.loaded || imageCache[this.src]) { //如果已緩存
- return this.render('loaded', true) // 使用緩存渲染圖片
- }
- this.render('loading', false) // 調(diào)用lazy中的 elRender()函數(shù), 用戶切換img的src顯示數(shù)據(jù),并觸發(fā)相應(yīng)的狀態(tài)的回調(diào)函數(shù)
- this.attempt++ // 嘗試次數(shù)累加
- this.record('loadStart') // 記錄當前狀態(tài)的時間
- // 異步加載圖片, 使用Image對象實現(xiàn)
- loadImageAsync({
- src: this.src
- }, data => {
- this.naturalHeight = data.naturalHeight
- this.naturalWidth = data.naturalWidth
- this.state.loaded = true
- this.state.error = false
- this.record('loadEnd')
- this.render('loaded', false) // 渲染 loaded狀態(tài)的 dom的內(nèi)容
- imageCache[this.src] = 1 // 當前圖片緩存在瀏覽器里面了
- }, err => {
- this.state.error = true
- this.state.loaded = false
- this.render('error', false)
- })
- }
5、loadImageAsync異步加載圖片方法,通過image對象實現(xiàn)的網(wǎng)絡(luò)請求。
- const loadImageAsync = (item, resolve, reject) => {
- let image = new Image()
- image.src = item.src
- image.onload = function () {
- resolve({
- naturalHeight: image.naturalHeight, // 圖片的 實際高度
- naturalWidth: image.naturalWidth,
- src: image.src
- })
- }
- image.onerror = function (e) {
- reject(e)
- }
- }
6、lazy class的update()函數(shù),也就是v-lazy指令綁定的數(shù)據(jù)發(fā)生改變的時候出發(fā)的回調(diào)函數(shù)。
- update (el, binding) { // 獲取當前dom綁定的 圖片src的數(shù)據(jù), 如果當前dom執(zhí)行過load過程, 重置當前dom的圖片數(shù)據(jù)和狀態(tài)
- let { src, loading, error } = this.valueFormatter(binding.value) // 當前綁定的value是 obj, 從中選取{src, loading, error}; 是string, 則用作src
- // 找到當前dom綁定的listener
- const exist = find(this.ListenerQueue, item => item.el === el)
- // 更新listener的狀態(tài)和狀態(tài)對應(yīng)的圖片資源
- exist && exist.update({
- src,
- loading,
- error
- })
- this.lazyLoadHandler()
- Vue.nextTick(() => this.lazyLoadHandler())
- }
【編輯推薦】