jQuery select images above the fold

2019-07-01 23:11发布

问题:

I am currently using the jQuery lazyload plugin to load images. I am using javascript to replace the src and data-original attributes. This causes a slight flicker on load. I am wondering if there is a way with jquery to select only the images below the fold or above the fold so that I can avoid this flicker.

var $imgs = $("img:not(.nolazy)");
$imgs.each( function(){
    var imgSrc = $(this).attr("src");
    $(this).attr("data-original",imgSrc).attr("src","gray.gif");
});
$imgs.lazyload({
      effect : "fadeIn"
});

Edit: @Jason Sperske great answer. This is the code that I have resolved the flickering issue with:

var wH = $(window).height();
var $imgs = $("img:not(.nolazy)");
$imgs.each( function(){
    var imgPosition = $(this).offset();
    if(imgPosition.top > wH){
        var imgSrc = $(this).attr("src");
        $(this).attr("data-original",imgSrc).attr("src","gray.gif");
    }
});
$imgs.lazyload({
      effect : "fadeIn"
});

回答1:

While there is no built in selector for this purpose you could iterate over them and look for position values that are greater than the window height. Ben Pickles (his SO profile) has implemented this into a filter called onScreen which you can use like a selector (note that it will still fetch all elements, but then pair down the list before you attempt to modify them, so the selector won't be any faster (actually slightly slower), but the reduced set of elements will be faster to update).