jQuery select images above the fold

独自空忆成欢 提交于 2020-01-24 09:21:29

问题


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).



来源:https://stackoverflow.com/questions/12485273/jquery-select-images-above-the-fold

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!