一、前言

当一个页面中请求的图片过多,而且图片太大,页面访问的速度是非常慢的,对用户的体验非常不友好;使用图片懒加载,可以减轻服务器的压力,增加页面的访问量,这里主要是总结一下我自己写的图片懒加载组件jQuery.imgLazyLoad;使用该组件应在img标签中设置一个imglazyload-src属性,存放图片地址。

二、应用实例demo

/**
* component: imgLazyLoad 2013/12/12 华子yjh
* invoking: jQuery.imgLazyLoad(options)
*
// 配置对象
options = {
container: 'body', // 外围容器,默认body
tabItemSelector: '', // Tab切换面板选择器
carouselItemSelector: '', // 图片轮播面板选择器
attrName: 'imglazyload-src' // 图片地址属性
diff: 300 // 预加载像素
}
*
*/

图片轮播懒加载:http://miiee.taobao.com
Tab切换图片懒加载:http://miiee.taobao.com/main.htm
浏览器滚动图片懒加载:http://miiee.taobao.com/themes/theme_151.htm

三、设计思路

1、处理浏览器下拉滚动

比较 $(window).scrollTop + $(window).height() 与 img.offset().top 的值,当图片在浏览器窗口中,开始加载图片

2、处理Tab切换 与 图片轮播

在处理Tab切换 与 图片轮播,组件提供了一个用于事件处理的函数 handleImgLoad,参数idx:

该参数对于图片轮播,是作为下一轮轮播面板的索引,将下一轮轮播面板中的所有图片预加载
对于Tab切换,则是作为tab项的索引,加载当前显示tab项中的所有图片

3、选择器处理

3.1、滚动下拉选择器的处理

在 配置对象中有一个attrName,是保持图片地址的一个属性 选择器为:img[config.attrName];

其次图片是显示的,如果隐藏,则不加载图片, 选择器为:img[config.attrName]:visible;

再次如果图片已加载,为其加上一个img-loaded的className,为了过滤已加载过的图片,选择器为:img[config.attrName]:visible:not(.img-loaded);

最后如果一个页面使用多次组件,第一次使用时,当配置对象container为body子元素,第二次应该过滤前一次container匹配元素中的图片,
依次类推,选择器为:img[config.attrName]:visible:not(.img-loaded):not(jQuery.imgLazyLoad.selectorCache)

3.2、Tab切换、图片轮播选择器的处理

在 配置对象中有tabItemSelector 或 carouselItemSelector ,结合事件处理函数的参数idx,获取当前Tab项或下一轮轮播面板中的图片
选择器为:tabItemSelector:eq(idx) img 或 carouselItemSelector:eq(idx) img

如果idx === undefined,选择器为:tabItemSelector:visible img 或 carouselItemSelector:eq(0) img
我是根据我自己写的jQuery组件自行判断的

四、组件源码

$.extend({
imgLazyLoad: function(options) {
var config = {
container: 'body',
tabItemSelector: '',
carouselItemSelector: '',
attrName: 'imglazyload-src',
diff: 0
};
$.extend( config, options || {} ); var $container = $(config.container),
offsetObj = $container.offset(),
compareH = $(window).height() + $(window).scrollTop(), // 判断容器是否为body子元素
bl = $.contains( document.body, $container.get(0) ), // 过滤缓存容器中的图片
notImgSelector = jQuery.imgLazyLoad.selectorCache ? ':not(' + jQuery.imgLazyLoad.selectorCache + ')' : '',
imgSelector = 'img[' + config.attrName + ']:visible' + notImgSelector,
$filterImgs = $container.find(imgSelector), // 用于阻止事件处理
isStopEventHandle = false, // 是否自动懒加载,为true时,绑定滚动事件
isAutoLazyload = false; // 缓存容器为body子元素的图片选择器
jQuery.imgLazyLoad.selectorCache = bl ? (jQuery.imgLazyLoad.selectorCache ? (jQuery.imgLazyLoad.selectorCache + ',' + config.container + ' img') : config.container + ' img') : jQuery.imgLazyLoad.selectorCache; function handleImgLoad(idx) {
if (isStopEventHandle) {
return;
}
/**
处理Tab切换,图片轮播,在处理$filterImgs时,没有过滤img:not(.img-loaded),因为只是在一个面板中,
还有其他面板,如果再次触发,可能$filterImgs.length为0,因此只能在外围容器中判断过滤图片length
*/
if ($container.find('img:not(.img-loaded)').length === 0) {
isStopEventHandle = true;
} var itemSelector = config.tabItemSelector || config.carouselItemSelector || '';
if (itemSelector) {
if (typeof idx !== undefined && idx >= 0) {
$filterImgs = $container.find(itemSelector).eq(idx).find('img');
}
else {
if (itemSelector === config.carouselItemSelector) {
$filterImgs = $container.find(itemSelector).eq(0).find('img');
}
else {
$filterImgs = $container.find(itemSelector + ':visible').find('img');
}
}
}
else {
$filterImgs = $filterImgs.not('.img-loaded'); // 自动懒加载,过滤已加载的图片
isAutoLazyload = true;
} // 当外围容器位置发生变化,需更新
offsetObj = $container.offset(); if ($filterImgs.length > 0) {
$filterImgs.each(function(idx, elem) {
var $target = $(elem),
targetTop = $target.offset().top,
viewH = $(window).height() + $(window).scrollTop() + config.diff; if (bl) {
$target.attr('src', $target.attr(config.attrName)).removeAttr(config.attrName).addClass('img-loaded');
}
// 内容在视窗中
if (viewH > targetTop) {
$target.attr('src', $target.attr(config.attrName)).removeAttr(config.attrName).addClass('img-loaded');
}
});
}
else {
// 处理滚动事件
isStopEventHandle = true;
$(window).unbind('resize scroll', handleImgLoad);
}
} handleImgLoad();
if (isAutoLazyload) {
$(window).bind('resize scroll', handleImgLoad);
} // 提供事件处理函数
return {
handleImgLoad: handleImgLoad
}
}
}); // 保存非body子元素容器下的图片选择器
jQuery.imgLazyLoad.selectorCache = '';

五、实例应用代码

// 轮播图片 懒加载
(function(){
var imgLazyLoadObj = $.imgLazyLoad({
container: '#first-block-switch',
carouselItemSelector: '.switch-content li'
});
$.switchable({
wrapSelector: '#first-block-switch',
contentSelector: '.switch-content',
prevBtnSelector: '.prev',
nextBtnSelector: '.next',
triggerSelector: '.switch-nav',
autoPlay: true,
duration: 300,
interval: 3000,
handleImgLoad: imgLazyLoadObj.handleImgLoad
});
}()); // 浏览器滚动 懒加载
$.imgLazyLoad({ diff: 300 });

转载请注明出处:博客园华子yjh

jQuery.imgLazyLoad图片懒加载组件的更多相关文章

  1. jQuery的图片懒加载

    jQuery的图片懒加载 function imgLazyLoad(options) { var settings = { Id: $('img'), threshold: 100, effectsp ...

  2. 使用jQuery实现图片懒加载原理

    原文:https://www.liaoxuefeng.com/article/00151045553343934ba3bb4ed684623b1bf00488231d88d000 在网页中,常常需要用 ...

  3. 带加载进度的Web图片懒加载组件Lazyload

    在Web项目中,大量的图片应用会导致页面加载时间过长,浪费不必要的带宽成本,还会影响用户浏览体验. Lazyload 是一个文件大小仅4kb的图片懒加载组件(不依赖其它第三方库),组件会根据用户当前浏 ...

  4. jQuery插件图片懒加载lazyload

    来自XXX的前言: 什么是ImageLazyLoad技术 在页面上图片比较多的时候,打开一张页面必然引起与服务器大数据量的 交互.尤其是对于高清晰的图片,占的几M的空间.ImageLazyLoad技术 ...

  5. jQuery实现图片懒加载

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. jquery <img> 图片懒加载 和 标签如果没有加载出图片或没有图片,就显示默认的图片

    参考链接:http://www.jq22.com/jquery-info390 或压缩包下载地址:链接:http://pan.baidu.com/s/1hsj8ZWw 密码:4a7s    下面是没有 ...

  7. 基于jquery的图片懒加载js

    function lazyload(option){ var settings={ defObj:null, defHeight: }; settings=$.extend(settings,opti ...

  8. [jQuery插件]手写一个图片懒加载实现

    教你做图片懒加载插件 那一年 那一年,我还年轻 刚接手一个ASP.NET MVC 的 web 项目, (C#/jQuery/Bootstrap) 并没有做 web 的经验,没有预留学习时间, (作为项 ...

  9. 前端实现图片懒加载(lazyload)的两种方式

    在实际的项目开发中,我们通常会遇见这样的场景:一个页面有很多图片,而首屏出现的图片大概就一两张,那么我们还要一次性把所有图片都加载出来吗?显然这是愚蠢的,不仅影响页面渲染速度,还浪费带宽.这也就是们通 ...

随机推荐

  1. C# winform窗体设计-数据库连接

    本篇文章内容主要是小编上课所学的总结 最近小编在学习C#中的数据库管理方面,主要学习到数据库的增删改查,查询学生平均分,最低分,最高分等操作 [本篇文章中小编主要讲解数据库的连接] 在C#中使用数据库 ...

  2. dedecms /plus/search.php SQL Injection && Local Variable Overriding

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 这个文件有两处注入漏洞 . $typeid变量覆盖导致ChannelTy ...

  3. 添加一个功能Action

    1,只用一个handler类,所有都事件的处理器都在一个handler类 handler要创建以Action为名称的方法 event要单独分开,继承KDEvent package com.kingde ...

  4. shell命令locate

    介绍 linux上做维护的时候经常会去查找某个文件路径 如果不需要特殊的查找匹配(比如时间 大小...) 格式化的输出(此处用find) 建议用locate命令 因为locate命令查找速度非常的快 ...

  5. A.Kaw矩阵代数初步学习笔记 10. Eigenvalues and Eigenvectors

    “矩阵代数初步”(Introduction to MATRIX ALGEBRA)课程由Prof. A.K.Kaw(University of South Florida)设计并讲授. PDF格式学习笔 ...

  6. Vijos 1816统计数字(计数排序)

    传送门 Description 某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*10^9).已知不相同的数不超过10000个,现在需要统计这些自然数各自出现的次数,并按照自 ...

  7. django views中提示cannot convert dictionary update sequence element #0 to a sequence错误

    def message(request): message_list = MessageBoard.objects.all().order_by('-pk') return render(reques ...

  8. 配置ASP.NET Web应用程序, 使之运行在medium trust

    这文章会向你展示, 怎么配置ASP.NET Web应用程序, 使之运行在medium trust.   如果你的服务器有多个应用程序, 你可以使用code access security和medium ...

  9. ThreadPoolExecutor机制

    一.概述 1.ThreadPoolExecutor作为java.util.concurrent包对外提供基础实现,以内部线程池的形式对外提供管理任务执行,线程调度,线程池管理等等服务: 2.Execu ...

  10. CSS3动画(性能篇)

    写在前面 高性能移动Web相较PC的场景需要考虑的因素也相对更多更复杂,我们总结为以下几点: 流量.功耗与流畅度. 在PC时代我们更多的是考虑体验上的流畅度,而在Mobile端本身丰富的场景下,需要额 ...