Should I always use .off ('load') ;?

On the portfolio website, where there are a lot of images, I check what the client load time is, and then serve either small or large images. But after loading a smaller set of images, I would like to swap them for larger images.

I used the .on ('load') handler, but when testing the page, I found that it continues to fire. I fixed this by adding the .off ('load') handler at the end.

$(this).on('load', function() {
  $(this).attr('src', $(this).data('src')).off('load');
  console.log('full size img are loading');
}).attr('src', srcNew);

So my question is:

In all the code snippets on the Internet, I never used this .off ('load') handler. Is this normal behavior?

Perhaps it is important that the function is in a loop? Here is the full function:

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();
    });
});

And here is the HTML:

<img data-src="img/photo.jpg" src="img/photo_s.jpg" alt="" />
+4
source share
1

, load . src , ; , load , . .off() , , . , . One().

+1

Source: https://habr.com/ru/post/1663953/


All Articles