DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript瀑布流式圖片懶加載實例
javascript瀑布流式圖片懶加載實例
編輯:關於JavaScript     

最近項目使用到了“懶加載”,現在更新一般,因為平時主要使移動端的開發所以庫文件使用的是zepto.js 。當然也可以和jQuery 通用。

代碼如下:

/**
 * Created by zhiqiang on 2015/10/14.
 * [email protected]
 * 圖片的懶加載
 **/
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;
 };
}

希望本文對大家學習javascript圖片懶加載有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved