How to trigger a lazyload (on-demand load) with JQuery

Lazyloading, or on-demand loading, is a convenient way to save bandwidth and server load. Requests for content are made only as the user scrolls down to each area of the page. For example, if you scroll down through an Amazon product page, you may notice that content starts to load on Ajax calls only as those areas come in to view.

This post is not about how to make an Ajax call. Instead, it’s about when to make the call. At the bottom of my page, I have a DIV called more. I want to load content into that DIV using an Ajax request whenever a user scrolls down and my DIV comes into view. So here is my DIV:

   1: <div id="more"></div>

Now, let’s find out the offset top height of my DIV using a JQuery offset() function. Put that into a variable.
   1: var position        = $("#more").offset().top

Next,  let’s find out the total document height, up to the current scrolled position. In other words, the window height + the height of the vertical scroll. Put that into another variable.
   1: var scllwidth        = $(window).scrollTop() + $(window).height()

At this point, I know the vertical, visible position of my document and the vertical position of my DIV. If the vertical, visible position of my document is greater than my DIV’s vertical position, that means my DIV has come into view and is ready for content to be loaded.
   1: if ( scllwidth > position) {
   2:  alert( "Time to Load Content! Ajax request goes here")
   3: }
Show/Hide Line Numbers . Full Screen . Plain

I can use a JQuery scroll() function to check these values whenever a user scrolls in the browser window.

   1: $(window).scroll( function() { alert("User scroll the page") } )

Here is everything put together. See how simple it is!

   1: function reloadq() {
   2:                 var position        = $("#more").offset().top            
   3:                 var scllwidth        = $(window).scrollTop() + $(window).height()
   4:                 if ( scllwidth > position) {
   5:                                 alert( "Time to Load Content! Ajax request goes here" )
   6:                 }
   7: }
   8: $(window).scroll( function() { reloadq() } )
Show/Hide Line Numbers . Full Screen . Plain

Just replace [ alert( "Time to Load Content! Ajax request goes here" ) ] with your own AJAX request. That's lazyload folks!

7 Comments :
Charles
Thursday 25 July 2013 09:21 AM
great tutorial, thanks share it.
Tommy
Friday 25 May 2012 04:33 AM
Thanks a lot!
Wednesday 18 April 2012 11:38 AM
Cheers ~0)
Wednesday 11 April 2012 12:51 AM
Excellent tutorial,
Thanks!
Mansoor
Thursday 29 March 2012 07:38 AM
Nice article ! Thx for sharing!
Tuesday 02 August 2011 05:36 AM
Very nice and simple! Thx for sharing!
Friday 22 October 2010 09:16 PM
Good job. Its simple. I like that and it allows others to modify for their purpose. I would add a timed delay to wait for the scroll to finish and add a check if the content was loaded already.