在一个拥有大量图像的porfolio网站上,我检查客户端的加载时间,然后提供小图或大图。但在加载较小的一组图像后,我想将它们交换出来以便放大图像。我应该总是使用.off('load');?
我为此使用了.on('load')处理函数,但是当测试页面时,我发现它一直在触发。我通过在最后添加.off('load')处理程序来修复它。
$(this).on('load', function() {
$(this).attr('src', $(this).data('src')).off('load');
console.log('full size img are loading');
}).attr('src', srcNew);
所以我的问题是:
在所有的代码片段在网上,我从来没有发现这种使用.off(“负荷”)处理的。这是正常的行为吗?
函数是否在循环中可能很重要?下面是完整的功能:
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
$(document).ready(function() {
$.fn.lazyLoad = function(){
if($(this).is('img[data-src]')) {
var lazy = $(this);
} else {
var lazy = $(this).find('img[data-src]');
};
$(lazy).each(function(){
if (loadTime > 1000) {
var src = $(this).data('src');
var srcPath = src.slice(0, -4);
var srcExt = src.slice(-4);
var srcNew = srcPath + '_s' + srcExt;
$(this).on('load', function() {
$(this).attr('src', $(this).data('src')).off('load');
console.log('full size img have been loaded');
}).attr('src', srcNew);
console.log('_s img have been loaded');
} else {
$(this).attr('src', $(this).data('src'));
}
});
};
$('.lazy').lazyLoad();
$('.slide').click(function() {
$(this).lazyLoad();
});
});
而且这里的HTML:
<img data-src="img/photo.jpg" src="img/photo_s.jpg" alt="" />
你能告诉你如何初始化插件吗? –
我在我的问题中添加了代码。 lazyLoad函数在所有具有.lazy类的元素上被调用,或者通过类.slide打开幻灯片。 – thomascs