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:
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: }
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() } )
Just replace [ alert( "Time to Load Content! Ajax request goes here" ) ] with your own AJAX request. That's lazyload folks!
Posted by Saman W Jayasekara at Sunday 26 September 2010 06:16 PM
.
This and That
.
JavaScript