Last active
June 5, 2016 12:31
-
-
Save black-black-cat/03a2ffccf6cfe829bfeb69a9b0ea8250 to your computer and use it in GitHub Desktop.
images lazy load 懒加载
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {Object} option | |
* @param {jQuery | String} option.defObj jQuery对象或作为选择器的字符串 | |
* @param {Number} opiton.defHeight 为负数时,则可以提前加载视口下方的图片资源 | |
*/ | |
function lazyload(option) { | |
var settings = { | |
// {jQuery | String} jQuery对象或作为选择器的字符串 | |
defObj: null, | |
// {Number} 为负数时,则可以提前加载视口下方的图片资源 | |
defHeight: 0 | |
}; | |
settings = $.extend({}, settings, option || {}); | |
var defObj = settings.defObj, | |
$imgs = (defObj instanceof $) ? defObj.find('img') : $(defObj).find('img'); | |
var pageTop = function() { | |
var d = document | |
, y = (navigator.userAgent.toLowerCase().match(/iPad/i) == 'ipad') ? window.pageYOffset : Math.max(d.documentElement.scrollTop, d.body.scrollTop); | |
return d.documentElement.clientHeight + y - settings.defHeight; | |
}; | |
var imgLoad = function() { | |
$imgs.each(function() { | |
if ($(this).offset().top <= pageTop()) { | |
var src3 = $(this).attr('lazy-src'); | |
if (src3) { | |
$(this).attr('src', src3).removeAttr('lazy-src'); | |
} | |
} | |
}); | |
}; | |
imgLoad(); | |
$(window).on('scroll', function() { | |
imgLoad(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment