当前位置: 首页 > news >正文

jquery图片懒加载

HTML、 

 <div><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg" src="默认图片地址"/><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg"  src="默认图片地址"/><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg"  src="默认图片地址"/><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg"  src="默认图片地址"/><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg"  src="默认图片地址"/><img class="lazyload" alt="" width="1000"  data-original="/skin/default/images/BB2.jpg"  src="默认图片地址"/></div>

lazyload.js

/*!* An jQuery | zepto plugin for lazy loading images.* author -> jieyou* see https://github.com/jieyou/lazyload* use some tuupola's code https://github.com/tuupola/jquery_lazyload (BSD)* use component's throttle https://github.com/component/throttle (MIT)*/
;(function(factory){if(typeof define === 'function' && define.amd){ // AMD// you may need to change `define([------>'jquery'<------], factory)` // if you use zepto, change it rely name, such as `define(['zepto'], factory)`define(['jquery'], factory)// define(['zepto'], factory)}else{ // Globalfactory(window.jQuery || window.Zepto)}
})(function($,undefined){var w = window,$window = $(w),defaultOptions = {threshold                   : 0,failure_limit               : 0,event                       : 'scroll',effect                      : 'show',effect_params               : null,container                   : w,data_attribute              : 'original',data_srcset_attribute       : 'original-srcset',skip_invisible              : true,appear                      : emptyFn,load                        : emptyFn,vertical_only               : false,check_appear_throttle_time  : 300,url_rewriter_fn             : emptyFn,no_fake_img_loader          : false,placeholder_data_img        : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC',// for IE6\7 that does not support data imageplaceholder_real_img        : 'http://ditu.baidu.cn/yyfm/lazyload/0.0.1/img/placeholder.png'// todo : 灏嗘煇浜涘睘鎬х敤global鏉ラ厤缃紝鑰屼笉鏄瘡娆″湪$(selector).lazyload({})鍐呴厤缃�},type // functionfunction emptyFn(){}type = (function(){var object_prototype_toString = Object.prototype.toStringreturn function(obj){// todo: compare the speeds of replace string twice or replace a regExpreturn object_prototype_toString.call(obj).replace('[object ','').replace(']','')}})()function belowthefold($element, options){var foldif(options._$container == $window){fold = ('innerHeight' in w ? w.innerHeight : $window.height()) + $window.scrollTop()}else{fold = options._$container.offset().top + options._$container.height()}return fold <= $element.offset().top - options.threshold}function rightoffold($element, options){var foldif(options._$container == $window){// Zepto do not support `$window.scrollLeft()` yet.fold = $window.width() + ($.fn.scrollLeft?$window.scrollLeft():w.pageXOffset)}else{fold = options._$container.offset().left + options._$container.width()}return fold <= $element.offset().left - options.threshold}function abovethetop($element, options){var foldif(options._$container == $window){fold = $window.scrollTop()}else{fold = options._$container.offset().top}// console.log('abovethetop fold '+ fold)// console.log('abovethetop $element.height() '+ $element.height())return fold >= $element.offset().top + options.threshold  + $element.height()}function leftofbegin($element, options){var foldif(options._$container == $window){// Zepto do not support `$window.scrollLeft()` yet.fold = $.fn.scrollLeft?$window.scrollLeft():w.pageXOffset}else{fold = options._$container.offset().left}return fold >= $element.offset().left + options.threshold + $element.width()}function checkAppear($elements, options){var counter = 0$elements.each(function(i,e){var $element = $elements.eq(i)if(($element.width() <= 0 && $element.height() <= 0) || $element.css('display') === 'none'){return}function appear(){$element.trigger('_lazyload_appear')// if we found an image we'll load, reset the counter counter = 0}// If vertical_only is set to true, only check the vertical to decide appear or not// In most situations, page can only scroll vertically, set vertical_only to true will improve performanceif(options.vertical_only){if(abovethetop($element, options)){// Nothing. }else if(!belowthefold($element, options)){appear()}else{if(++counter > options.failure_limit){return false}}}else{if(abovethetop($element, options) || leftofbegin($element, options)){// Nothing. }else if(!belowthefold($element, options) && !rightoffold($element, options)){appear()}else{if(++counter > options.failure_limit){return false}}}})}// Remove image from array so it is not looped next time. function getUnloadElements($elements){return $elements.filter(function(i,e){return !$elements.eq(i)._lazyload_loadStarted})}// throttle : https://github.com/component/throttle , MIT Licensefunction throttle (func, wait) {var ctx, args, rtn, timeoutID // cachingvar last = 0return function throttled () {ctx = thisargs = argumentsvar delta = new Date() - lastif (!timeoutID)if (delta >= wait) call()else timeoutID = setTimeout(call, wait - delta)return rtn}function call () {timeoutID = 0last = +new Date()rtn = func.apply(ctx, args)ctx = nullargs = null}}if(!$.fn.hasOwnProperty('lazyload')){$.fn.lazyload = function(options){var $elements = this,isScrollEvent,isScrollTypeEvent,throttleCheckAppearif(!$.isPlainObject(options)){options = {}}$.each(defaultOptions,function(k,v){if($.inArray(k,['threshold','failure_limit','check_appear_throttle_time']) != -1){ // these params can be a stringif(type(options[k]) == 'String'){options[k] = parseInt(options[k],10)}else{options[k] = v}}else if(k == 'container'){ // options.container can be a seletor string \ dom \ jQuery objectif(options.hasOwnProperty(k)){   if(options[k] == w || options[k] == document){options._$container = $window}else{options._$container = $(options[k])}}else{options._$container = $window}delete options.container}else if(defaultOptions.hasOwnProperty(k) && (!options.hasOwnProperty(k) || (type(options[k]) != type(defaultOptions[k])))){options[k] = v}})isScrollEvent = options.event == 'scroll'throttleCheckAppear = options.check_appear_throttle_time == 0?checkAppear:throttle(checkAppear,options.check_appear_throttle_time)// isScrollTypeEvent cantains custom scrollEvent . Such as 'scrollstart' & 'scrollstop'// https://github.com/search?utf8=%E2%9C%93&q=scrollstartisScrollTypeEvent = isScrollEvent || options.event == 'scrollstart' || options.event == 'scrollstop'$elements.each(function(i,e){var element = this,$element = $elements.eq(i),placeholderSrc = $element.attr('src'),originalSrcInAttr = $element.attr('data-'+options.data_attribute), // `data-original` attribute valueoriginalSrc = options.url_rewriter_fn == emptyFn?originalSrcInAttr:options.url_rewriter_fn.call(element,$element,originalSrcInAttr),originalSrcset = $element.attr('data-'+options.data_srcset_attribute),isImg = $element.is('img')if($element._lazyload_loadStarted == true || placeholderSrc == originalSrc){$element._lazyload_loadStarted = true$elements = getUnloadElements($elements)return}$element._lazyload_loadStarted = false// If element is an img and no src attribute given, use placeholder. if(isImg && !placeholderSrc){// For browsers that do not support data image.$element.one('error',function(){ // `on` -> `one` : IE6 triggered twice error event sometimes$element.attr('src',options.placeholder_real_img)}).attr('src',options.placeholder_data_img)}// When appear is triggered load original image. $element.one('_lazyload_appear',function(){var effectParamsIsArray = $.isArray(options.effect_params),effectIsNotImmediacyShowfunction loadFunc(){// In most situations, the effect is immediacy show, at this time there is no need to hide element first// Hide this element may cause css reflow, call it as less as possibleif(effectIsNotImmediacyShow){// todo: opacity:0 for fadeIn effect$element.hide()}if(isImg){// attr srcset firstif(originalSrcset){$element.attr('srcset', originalSrcset)}if(originalSrc){$element.attr('src', originalSrc)}}else{$element.css('background-image','url("' + originalSrc + '")')}if(effectIsNotImmediacyShow){$element[options.effect].apply($element,effectParamsIsArray?options.effect_params:[])}$elements = getUnloadElements($elements)}if(!$element._lazyload_loadStarted){effectIsNotImmediacyShow = (options.effect != 'show' && $.fn[options.effect] && (!options.effect_params || (effectParamsIsArray && options.effect_params.length == 0)))if(options.appear != emptyFn){options.appear.call(element, $element, $elements.length, options)}$element._lazyload_loadStarted = trueif(options.no_fake_img_loader || originalSrcset){if(options.load != emptyFn){$element.one('load',function(){options.load.call(element, $element, $elements.length, options)})}loadFunc()}else{$('<img />').one('load', function(){ // `on` -> `one` : IE6 triggered twice load event sometimesloadFunc()if(options.load != emptyFn){options.load.call(element, $element, $elements.length, options)}}).attr('src',originalSrc)}}})// When wanted event is triggered load original image // by triggering appear.                              if (!isScrollTypeEvent){$element.on(options.event, function(){if (!$element._lazyload_loadStarted){$element.trigger('_lazyload_appear')}})}})// Fire one scroll event per scroll. Not one scroll event per image. if(isScrollTypeEvent){options._$container.on(options.event, function(){throttleCheckAppear($elements, options)})}// Check if something appears when window is resized. // Force initial check if images should appear when window is onload. $window.on('resize load', function(){throttleCheckAppear($elements, options)})// Force initial check if images should appear. $(function(){throttleCheckAppear($elements, options)})return this}}
})

 js

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="lazyload.js"></script>
<script type="text/javascript">
$(function() {$("img.lazyload").lazyload();
});
</script>

http://www.lryc.cn/news/410416.html

相关文章:

  • 【端口】-
  • 【研发日记】Matlab/Simulink技能解锁(十一)——Stateflow中的en、du、ex应用对比
  • 《学会 SpringMVC 系列 · 剖析篇(上)》
  • 【Vulnhub系列】Vulnhub_SecureCode1靶场渗透(原创)
  • 【C语言】结构体详解 -《探索C语言的 “小宇宙” 》
  • 基于DTW距离的KNN算法实现股票高相似筛选案例
  • GD32 - IIC程序编写
  • 将项目部署到docker容器上
  • 免费【2024】springboot宠物美容机构CRM系统设计与实现
  • 搞懂数据结构与Java实现
  • Stable Diffusion 图生图
  • 语言转文字
  • ref函数
  • 7/30 bom和dom
  • 【Golang 面试 - 进阶题】每日 3 题(五)
  • MySQL,GROUP BY子句的作用是什么?having和where的区别在哪里说一下jdbc的流程
  • 1._专题1_双指针_C++
  • Spring集成ES
  • 力扣高频SQL 50题(基础版)第二十六题
  • WIFI 接收机和发射机同步问题+CFO/SFO频率偏移问题
  • ubuntu安装并配置flameshot截图软件
  • 【Linux】CentOS更换国内阿里云yum源(超详细)
  • Leetcode49. 字母异位词分组(java实现)
  • OpenJudge | 字符串中最长的连续出现的字符
  • 11day-C++list容器使用
  • docker 常用管理命令及数据备份
  • 前端开发:Vue2.0桌面组件库-Element
  • Java常见的面试二
  • 【Qt】QLCDNumberQProgressBarQCalendarWidget
  • C++ 代码实现局域网即时通信功能 (windows 系统 客户端)