一、前言

当一个页面中请求的图片过多,而且图片太大,页面访问的速度是非常慢的,对用户的体验非常不友好;使用图片懒加载,可以减轻服务器的压力,增加页面的访问量,这里主要是总结一下我自己写的图片懒加载组件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. 【poj3764】 The xor-longest Path

    http://poj.org/problem?id=3764 (题目链接) 今天的考试题,看到异或就有点虚,根本没往正解上想.. 题意 给出一棵带权树,请找出树上的一条路径,使其边上权值的异或和最大. ...

  2. bzoj3262: 陌上花开(树套树)

    #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...

  3. Cache Helper类

    using System; using System.Collections.Generic; using System.Web; using System.Collections; using Sy ...

  4. javaBean和Servlet有什么区别

    1.javabean无非就是里面有些set和get方法 2.servlet用来处理一些逻辑层 3.javabean.servlet.jsp分别对应M(odel).C(ontroller).V(iew) ...

  5. squid清除缓存

    客户经常要求清除缓存  由于CDN后台只能支持单个url的 所以目录级别的只能用脚本 example:清除 www.123.com 下所以的缓存 #!/bin/bash TODAY=`date +%Y ...

  6. MVC5-9 今天讲三个Descriptor

    ControllerDescriptor.ActionDescriptor.ParmaterDescriptor 看名字一脸懵逼,这是做什么的呢?可别小看它们,它们在MVC中扮演着尤为重要的角色. 思 ...

  7. Linux rsync网站目录同步功能的实现

    实现目标: 172.16.1.64服务器上的/var/www/sw_service目录,与172.16.1.60服务器上的/var/www/sw_service目录实现同步, 即1.60主动向1.64 ...

  8. HTML5系列四(WebWorker、地理定位)

    WebWorker简单应用 先从一个简单例子说起,计算数值加法 <script> var worker = new Worker('sumCalculate.js'); worker.on ...

  9. KEGG and Gene Ontology Mapping in Bioinformatic Method

    使用KOBAS进行KEGG pathway和Gene Ontology分析 Article from Blog of Alfred-Feng http://blog.sina.com.cn/u/170 ...

  10. Yocto开发笔记之《网卡配置》(QQ交流群:519230208)

    QQ群:519230208,为避免广告骚扰,申请时请注明 “开发者” 字样 ============================================== # ifconfig -a # ...