Load (Lazy Loading) a Div whenever the DIV gets visible for the first time

前端 未结 4 1531
灰色年华
灰色年华 2020-12-02 19:10

I want to enable a lazy loading for the contents of my website.

Just like Jquery Image loading http://www.appelsiini.net/projects/lazyload that is valid only for ima

4条回答
  •  一整个雨季
    2020-12-02 19:34

    I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:

    $(document).ready(function(){
       $(window).scroll(lazyload);
       lazyload();
    });
    

    Also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window, it should be visible (or in this case: loaded). Your function lazyload() might look like this:

    function lazyload(){
       var wt = $(window).scrollTop();    //* top of the window
       var wb = wt + $(window).height();  //* bottom of the window
    
       $(".ads").each(function(){
          var ot = $(this).offset().top;  //* top of object (i.e. advertising div)
          var ob = ot + $(this).height(); //* bottom of object
    
          if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
             $(this).html("here goes the iframe definition");
             $(this).attr("loaded",true);
          }
       });
    }
    

    I tested this on all major browsers and even on my iPhone. It works like a charm!!

提交回复
热议问题