JavaScript瀑布流图片懒加载实现与插件化优化

作者:缓存笔记时间:2026-10-29 22:18:32浏览:358

本文深入解析JavaScript瀑布流图片懒加载的实现原理,重点介绍通过配置参数如mobileHeight和loadNum优化首屏加载与滚动加载性能。文章展示了从基础逻辑到使用$.extend合并配置,再到采用插件化思想封装代码的完整优化过程,帮助开发者提升页面加载效率并实现代码复用。

引言与背景

此前曾撰写过关于图片“懒加载”的文章,近期整理文件时重新审视了旧代码,发现其中存在多处可优化空间。本文将结合前作《javascript瀑布流式图片懒加载实例》,进一步探讨图片懒加载的相关技术与改进方法。

懒加载核心原理

图片“懒加载”的核心目的在于按需加载,即仅在图片即将显示时才进行加载,从而避免一次性加载所有图片造成的网络带宽浪费。

基础实现与配置优化

首先回顾一段基础代码示例:


 var conf = {
   'loadfirst': true,
   'loadimg': true
  };

  for (var item in conf) {
   if (item in co) {
    conf.item = co.item;
   }
  }

原代码旨在实现用户配置与默认配置的合并,但这种写法不够优雅。现采用$.extend方法进行优化,具体实现如下:


_this.setting = {
   "mobileHeight": 0, //扩展屏幕的高度,使第一屏加载个数可配置
   "loadNum": 1 //滚动时,当前节点之后加载个数
  };

  $.extend(_this.setting, _this.getSetting());

关键参数详解

此处重点介绍新增的两个关键参数:mobileHeight和loadNum。

mobileHeight用于设定移动端视口高度,该值越大,首屏预加载的图片数量越多。

loadNum定义滚动加载时的批量加载数量,即当当前节点进入可视区域后,一次性加载其后若干个节点,从而提升图片加载速度。

早期的代码实现方式如下:


_this.loadFirstScreen = function() {
   if (conf.loadfirst) {
    lazyNode.each(function(i) {
     currentNodeTop = $(this).offset().top;
     //这里的800就是上面提到的mobileHeight
     if (currentNodeTop < mobileHeight + 800) {
      _this.replaceImgSrc($(this));
     }
    });
   }
  };

_this.loadImg = function() {
   if (conf.loadimg) {
    $(window).on('scroll', function() {
     var imgLazyList = $('[node-type=imglazy]', node);
     //这里的5就是上面提到的loadNum
     for (var i = 0; i < 5; i++) {
      _this.replaceImgSrc(imgLazyList.eq(i));
     }
    });
   }
  };

基于可配置化的思路,优化后的代码如下所示:


loadFirstSrceen: function() {
   // 加载首屏
   var _this = this;
   var currentNodeTop;
   var imgNodeList = _this.imgNode;
   $(imgNodeList).each(function() {
    currentNodeTop = $(this).offset().top;
    if (currentNodeTop < _this.mobileHeight() + _this.setting.mobileHeight) {
     _this.replaceImgSrc($(this));
    }
   });
  },
  scrollLoadImg: function() {
   //滚动的时候加载图片
   var _this = this;
   var currentNodeTop;
   var scrollTop = $('body').scrollTop();
   var imgLazyList = $('[node-type=imglazy]');

   $(imgLazyList).each(function() {
    currentNodeTop = $(this).offset().top;
    if (currentNodeTop - scrollTop < _this.mobileHeight()) {
     //加载当前节点后的规定个数节点
     for (var i = 0, len = _this.setting.loadNum; i < len; i++) {
      _this.replaceImgSrc($(imgLazyList).eq(i));
     }
     return false;
    }
   });
  }

插件化封装与总结

更为重要的是,按照编写插件的标准思想来重构代码结构,示例代码如下:


;(function($) {
 var LoadImgLazy = function(imgNode) {
  var _this = this;
  _this.imgNode = imgNode;

  _this.setting = {
   "mobileHeight": 0, //扩展屏幕的高度,使第一屏加载个数可配置
   "loadNum": 1 //滚动时,当前节点之后加载个数
  };

  $.extend(_this.setting, _this.getSetting());

  _this.loadFirstSrceen();
  $(window).on('scroll', function() {
   _this.scrollLoadImg();
  });


 };

 LoadImgLazy.prototype = {
  mobileHeight: function() {
   return $(window).height();
  },
  loadFirstSrceen: function() {
   // 加载首屏
   var _this = this;
   var currentNodeTop;
   var imgNodeList = _this.imgNode;
   $(imgNodeList).each(function() {
    currentNodeTop = $(this).offset().top;
    if (currentNodeTop < _this.mobileHeight() + _this.setting.mobileHeight) {
     _this.replaceImgSrc($(this));
    }
   });
  },
  scrollLoadImg: function() {
   //滚动的时候加载图片
   var _this = this;
   var currentNodeTop;
   var scrollTop = $('body').scrollTop();
   var imgLazyList = $('[node-type=imglazy]');

   $(imgLazyList).each(function() {
    currentNodeTop = $(this).offset().top;
    if (currentNodeTop - scrollTop < _this.mobileHeight()) {
     //加载当前节点后的规定个数节点
     for (var i = 0, len = _this.setting.loadNum; i < len; i++) {
      _this.replaceImgSrc($(imgLazyList).eq(i));
     }
     return false;
    }
   });
  },
  replaceImgSrc: function(loadImgNode) {
   //动态替换图片
   var srcValue;
   var imgDataSrc;
   var _this = this;
   var imgUrlList = $(loadImgNode).find('img[data-lazysrc]');

   if (imgUrlList.length > 0) {
    imgUrlList.each(function(i) {
     imgDataSrc = $(this).attr('data-lazysrc');
     srcValue = $(this).attr('src');
     if (srcValue === '#') {
      if (imgDataSrc) {
       $(this).attr('src', imgDataSrc);
       $(this).removeAttr('data-lazysrc');
      }
     }
    });
    //移除已经运行过懒加载节点的node-type 对性能提升
    $(loadImgNode).removeAttr('node-type');
   }
  },
  getSetting: function() {
   var userSetting = $('[lazy-setting]').attr('lazy-setting');
   if (userSetting && userSetting !== '') {
    return $.parseJSON(userSetting);
   } else {
    return {};
   }
  },
  destory: function() {
   //销毁方法区
   $(window).off('scroll');
  }
 };

 LoadImgLazy.init = function(imgNode) {
  new this(imgNode);
 };

 window.LoadImgLazy = LoadImgLazy;

})(Zepto);

通过本文的解析,希望读者能对JavaScript瀑布流式图片懒加载有更深入的理解,并掌握相应的优化技巧,感谢阅读。

作者最新文章