最近專案裡用到了圖片懶加載。因為平常主要做移動端開發,專案裡的 DOM 庫用的是 zepto.js,寫法與 jQuery 幾乎一致,直接換成 jQuery 也能跑。
先把完整程式碼放這裡,後面再拆解:
/** * Created by zhiqiang on 2015/10/14. * hpuhouzhiqiang@gmail.com * 圖片的懶加載 **/ function loadImgLazy(node) { var lazyNode = $('[node-type=imglazy]', node), mobileHeight, lazyOffSetHeight, tempHeight, currentNodeTop, imgObject, imgDataSrc, localUrl; localUrl = location.href; // 獲取當前浏覽器可視區域的高度 mobileHeight = $(window).height(); return function(co) { var conf = { 'loadfirst': true, 'loadimg': true }; for (var item in conf) { if (item in co) { conf[item] = co[item]; } } var that = {}; var _this = {}; /** * [replaceImgSrc 動態替換節點中的src] * @param {[type]} tempObject [description] * @return {[type]} [description] */ _this.replaceImgSrc = function(tempObject) { var srcValue; $.each(tempObject, function(i, item) { imgObject = $(item).find('img[data-lazysrc]'); imgObject.each(function(i) { imgDataSrc = $(this).attr('data-lazysrc'); srcValue = $(this).attr('src'); if (srcValue == '#') { if (imgDataSrc) { $(this).attr('src', imgDataSrc); $(this).removeAttr('data-lazysrc'); } } }); }); }; /** * 首屏判斷屏幕上是否出現imglazy節點,有的話就加載圖片 * @param {[type]} i) { currentNodeTop [description] * @return {[type]} [description] */ _this.loadFirstScreen = function() { if (conf.loadfirst) { lazyNode.each(function(i) { currentNodeTop = $(this).offset().top; if (currentNodeTop < mobileHeight + 800) { _this.replaceImgSrc($(this)); } }); } }; //當加載過首屏以後按照隊列加載圖片 _this.loadImg = function() { if (conf.loadimg) { $(window).on('scroll', function() { var imgLazyList = $('[node-type=imglazy]', node); for (var i = 0; i < 5; i++) { _this.replaceImgSrc(imgLazyList.eq(i)); } }); } }; that = { replaceImgSrc: _this.replaceImgSrc(), mobileHeight: mobileHeight, objIsEmpty: function(obj) { for (var item in obj) { return false; } return true; }, destory: function() { if (_this) { $.each(_this, function(i, item) { if (item && item.destory) { item.destory(); } }); _this = null; } $(window).off('scroll'); } }; return that; }; }
用自訂屬性存放真實網址。HTML 裡的圖片先寫成 src="#",真正的位址放在 data-lazysrc 上,並以 node-type="imglazy" 標記尚未載入的容器。瀏覽器因此不會在開頁時就去抓這些圖。
首屏與捲動分兩段處理。loadFirstScreen 負責開頁當下已在視窗內的圖,判定條件是元素的 offsetTop 小於視窗高度加上一段緩衝(程式碼裡寫死 800px);loadImg 則掛在 scroll 事件上,每次往下載入幾個節點。
替換完成就清掉標記。replaceImgSrc 把 data-lazysrc 的值寫回 src 後,會移除該屬性,這樣同一張圖不會被重複處理。
記得回收。destory 會逐一呼叫內部資源的清理方法並 off('scroll'),在單頁應用裡換頁時尤其重要,否則監聽器會越積越多。
這是最直觀的一版實作,好懂、好改。若要把 800 和 5 這類寫死的數字抽成設定,或改用建構函式加 prototype 的插件結構,可以參考後續的優化篇。