How do you make images load lazily only when they are in the viewport?

前端 未结 4 1329
一个人的身影
一个人的身影 2020-12-01 03:04

I am seeing a lot of sites these days, mainly tutorial sites that have a lot of images and they only load images further down the page once they come into the view port?

4条回答
  •  被撕碎了的回忆
    2020-12-01 03:59

    Replace your images with placeholders (e.g. just change the "src" attribute to something else so the image won't load, but the url will still be accessible), and then bind the window scroll event to a function which will find all images at the current scroll position, and swap the image src into a real img tag.

    Here's the code. It's untested, but this should be the basic idea:

    
    
    $(document).ready(function(){
    
      $(window).scroll(function(){
        $('img[realsrc]').each(function(i){
          var t = $(this);
          if(t.position().top > ($(window).scrollTop()+$(window).height()){
            t.attr('src', t.attr('realsrc')); // trigger the image load
            t.removeAttr('realsrc'); // so we only process this image once
          }
        });
      })
    
    });
    

提交回复
热议问题