原理簡(jiǎn)述
vue-lazyload是通過指令的方式實(shí)現(xiàn)的乙嘀,定義的指令是v-lazy指令
指令被bind時(shí)會(huì)創(chuàng)建一個(gè)listener,并將其添加到listener queue里面, 并且搜索target dom節(jié)點(diǎn),為其注冊(cè)dom事件(如scroll事件)
上面的dom事件回調(diào)中,會(huì)遍歷listener queue里的listener询张,判斷此listener綁定的dom是否處于頁(yè)面中perload的位置,如果處于則加載異步加載當(dāng)前圖片的資源
同時(shí)listener會(huì)在當(dāng)前圖片加載的過程的loading涎拉,loaded瑞侮,error三種狀態(tài)觸發(fā)當(dāng)前dom渲染的函數(shù),分別渲染三種狀態(tài)下dom的內(nèi)容
源碼解析
- 在組件install安裝時(shí)鼓拧,調(diào)用LazyClass返回了一個(gè)class對(duì)象半火,然后創(chuàng)建了一個(gè)class實(shí)例。
- 其核心是
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的底部是否到達(dá)了preload的位置酌住,X軸同理店归。
}
- 主要操作:找到對(duì)應(yīng)的target(用于注冊(cè)dom事件的dom節(jié)點(diǎn);比如:頁(yè)面滾動(dòng)的dom節(jié)點(diǎn))酪我,為其注冊(cè)dom事件消痛;為當(dāng)前dom創(chuàng)建Listenr并添加到listener queue中。最后代用lazyLoadHandler()函數(shù)都哭,加載圖片秩伞。
- 當(dāng)滿足條件,調(diào)用load()函數(shù)異步加載圖片欺矫。
load () {
// 如果當(dāng)前嘗試加載圖片的次數(shù)大于指定的次數(shù), 并且當(dāng)前狀態(tài)還是錯(cuò)誤的, 停止加載動(dòng)作
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') // 記錄當(dāng)前狀態(tài)的時(shí)間
// 異步加載圖片, 使用Image對(duì)象實(shí)現(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 // 當(dāng)前圖片緩存在瀏覽器里面了
}, err => {
this.state.error = true
this.state.loaded = false
this.render('error', false)
})
}
- loadImageAsync異步加載圖片方法纱新,通過image對(duì)象實(shí)現(xiàn)的網(wǎng)絡(luò)請(qǐng)求
const loadImageAsync = (item, resolve, reject) => {
let image = new Image()
image.src = item.src
image.onload = function () {
resolve({
naturalHeight: image.naturalHeight, // 圖片的 實(shí)際高度
naturalWidth: image.naturalWidth,
src: image.src
})
}
image.onerror = function (e) {
reject(e)
}
}
- lazy class的update()函數(shù),也就是v-lazy指令綁定的數(shù)據(jù)發(fā)生改變的時(shí)候出發(fā)的回調(diào)函數(shù)
update (el, binding) { // 獲取當(dāng)前dom綁定的 圖片src的數(shù)據(jù), 如果當(dāng)前dom執(zhí)行過load過程, 重置當(dāng)前dom的圖片數(shù)據(jù)和狀態(tài)
let { src, loading, error } = this.valueFormatter(binding.value) // 當(dāng)前綁定的value是 obj, 從中選取{src, loading, error}; 是string, 則用作src
// 找到當(dāng)前dom綁定的listener
const exist = find(this.ListenerQueue, item => item.el === el)
// 更新listener的狀態(tài)和狀態(tài)對(duì)應(yīng)的圖片資源
exist && exist.update({
src,
loading,
error
})
this.lazyLoadHandler()
Vue.nextTick(() => this.lazyLoadHandler())
}
總結(jié)
作者代碼結(jié)構(gòu)的設(shè)計(jì)穆趴,我們可以看到Lazy load模塊和listener模塊他們的業(yè)務(wù)職責(zé)分工明確脸爱。lazy負(fù)責(zé)和dom相關(guān)的處理,包括為dom創(chuàng)建listener未妹,為target注冊(cè)dom事件簿废,渲染dom;而listener只負(fù)責(zé)狀態(tài)的控制络它,在不同狀態(tài)執(zhí)行不同的業(yè)務(wù)捏鱼。
vue中定義了lazy、lazy-container指令酪耕,方便通過attrs的形式進(jìn)行配置导梆。
注:v-lazy.container在for循環(huán)渲染中,需要配置key否則會(huì)有”bug“迂烁,git中很多issue提到這個(gè)問題看尼。
my research
- 前提概要:第一次add觸發(fā)render正常,第二次update如果數(shù)量小于等于前一次盟步,第二次不會(huì)update且沿用前一個(gè)數(shù)組的圖片藏斩。
- 經(jīng)過排查根源是attrs的確是更新了,但是v-lazy沒有根據(jù)變化觸發(fā)lazy.add添加key后是能正常執(zhí)行
- 因?yàn)椴煌琸ey會(huì)重新添加元素重新觸發(fā)bind即執(zhí)行add因此正常顯示
- 埋點(diǎn)跟蹤確定是update函數(shù)的書寫問題却盘。修改attr觸發(fā)update通過ListenerQueue去取exist項(xiàng)但是loaded狀態(tài)的圖片會(huì)去掉listener因?yàn)樗募虞d使命已完成狰域,因此就不會(huì)執(zhí)行我們需要的update媳拴。
- 仔細(xì)分析應(yīng)該不算是bug因?yàn)樽髡弑疽鈛pdate就是用作未加載出的圖片更新src,對(duì)于已加載的圖片作整體update刷新應(yīng)該通過key重新add是最佳體驗(yàn)兆览。