2016-12-16 48 views
4

在一个拥有大量图像的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="" /> 
+0

你能告诉你如何初始化插件吗? –

+0

我在我的问题中添加了代码。 lazyLoad函数在所有具有.lazy类的元素上被调用,或者通过类.slide打开幻灯片。 – thomascs

回答

1

你的功能不断被调用,因为load事件不断被触发。当您更改图像的src属性时,浏览器将加载新的源数据;完成后,该元素上的新load事件将触发事件侦听器,与以前相同。 可以在函数的末尾使用.off()以确保它只运行一次。通过使用.one()可以获得相同的行为。

+0

.one()似乎是我最好的选择。我从来没有意识到事件监听器仍然会监听它所触发的功能。 – thomascs

相关问题