Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

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

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

I want to do it for the content (DIV's).

Suppose we have a long page then i want to download the div as they becomes visible.

I will download the content using JSON or PageMethods. But i want the code that will execute the function for loading contents.

So whether we can somehow find this that div is visible only scrolling down.

Means i need to use some scroll events but dont know how.

Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...