Javascript實現圖片懶載入外掛程式的方法_javascript技巧

來源:互聯網
上載者:User

前言

網路上各大論壇,尤其是一些圖片類型的網站上,在圖片載入時均採用了一種名為懶載入的方式,具體表現為,當頁面被請求時,只載入可視地區的圖片,其它部分的圖片則不載入,只有這些圖片出現在可視地區時才會動態載入這些圖片,從而節約了網路頻寬和提高了初次載入的速度,具體實現的技術並不複雜,下面分別對其說明。

Web 圖片的懶載入就是通過讀取img元素,然後獲得img元素的data-src(也可以約定為其他屬性名稱)屬性的值,並賦予img的src,從而實現動態載入圖片的機制。

這裡需要注意的是: img在初始化的時候不要設定src屬性,因為即使設定 src='' 瀏覽器也會嘗試載入圖片。

一個簡單的圖片懶載入共涉及兩個方面

1. HTML 約定

我們首先需要給準備實施懶載入的img元素添加指定的class 這裡為m-lazyload ,同時將img src賦值給 data-src屬性。

具體樣本為:

<img class="m-lazyload" data-src="imgUrl">

2. JavaScript 實現

動態載入總共分為以下幾個步驟,這裡每個步驟都將被拆分為獨立的函數

1. 添加頁面滾動監聽事件

window.addEventListener('scroll', _delay, false);function _delay() { clearTimeout(delay); delay = setTimeout(function () { _loadImage(); }, time);}

2. 當觸發監聽事件時會執行 _loadImage 函數,該函數負責載入圖片

function _loadImage() { for (var i = imgList.length; i--;) { var el = imgList[i]; if (_isShow(el)) {  el.src = el.getAttribute('data-src');  el.className = el.className.replace(new RegExp("(\\s|^)" + _selector.substring(1, _selector.length) + "(\\s|$)"), " ");  imgList.splice(i, 1); } }}

雖然執行了_loadImage函數,但是我們得知道哪些圖片需要被載入,這裡的判斷依據是什麼呢?

依據就是判斷該圖片是否在當前視窗的可視地區內,在這裡我們封裝一個_isShow函數來實現

function _isShow(el) { var coords = el.getBoundingClientRect(); return ( (coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset));}

自此一個圖片載入的閉環就形成了

當網頁滾動的事件被觸發 -> 執行載入圖片操作 -> 判斷圖片是否在可視地區內 -> 在,則動態將data-src的值賦予該圖片。

太簡單了?

事實就是如此!!!

如此簡單,不妨擴充一下

添加一些自訂參數,誰都喜歡自訂,不是嗎?

支援iScroll, iScroll是一個高效能,資源佔用少,無依賴,多平台的javascript滾動外掛程式。

這裡我們做了些最佳化

圖片載入後移除選取器,避免重複判斷。

緩衝img元素結合,減少dom元素查詢效能損耗

擴充prototype添加getNode方法,支援分頁資料懶載入(由於我們之前緩衝了dom元素)

OK!說了這麼多,show me the code 吧!

(function () { var imgList = [], // 頁面所有img元素集合 delay, // setTimeout 對象 offset, //位移量,用於指定圖片距離可視地區多少距離,進行載入 time, // 延遲載入時間 _selector; // 選取器 預設為 .m-lazyload function _isShow(el) { var coords = el.getBoundingClientRect(); return ( (coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset)); } function _loadImage() { for (var i = imgList.length; i--;) {  var el = imgList[i];  if (_isShow(el)) {  el.src = el.getAttribute('data-src');  el.className = el.className.replace(new RegExp("(\\s|^)" + _selector.substring(1, _selector.length) + "(\\s|$)"), " ");  imgList.splice(i, 1);  } } } function _delay() { clearTimeout(delay); delay = setTimeout(function () {  _loadImage(); }, time); } function ImageLazyload(selector, options) { var defaults = options || {}; offset = defaults.offset || 0; time = defaults.time || 250; _selector = selector || '.m-lazyload'; this.getNode(); _delay();//避免首次載入未觸發touch事件,主動觸發一次載入函數 if (defaults.iScroll) {  defaults.iScroll.on('scroll', _delay);  defaults.iScroll.on('scrollEnd', _delay); } else {  window.addEventListener('scroll', _delay, false); } } ImageLazyload.prototype.getNode = function () { imgList = []; var nodes = document.querySelectorAll(_selector); for (var i = 0, l = nodes.length; i < l; i++) {  imgList.push(nodes[i]); } };})();

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用圖片懶載入的時候能有所協助,如果有有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.