Mental Jetsam

By Peter Finch

Delayed loading of images and content using JQuery

Posted by pcfinch on August 25, 2010

I’m new to JQuery, so please forgive me if this is not the best way to do this. I created this JQuery script to “lazy load” parts of a HTML page only when they appear in the window. It works great if you have a lot of large images and only want to load them when they are visible to the user, or if you have a section in the document [like comments at the bottom of the page] that you only need loaded when the user looks at it.

(function($) {
  $.fn.lazyload = function(func) {
    var nodes = [] ;
    this.each(function() { nodes.push($(this)) } ) ;
    var scrollFunc = function() {
      var topOffset = $(window).scrollTop() ;
      var bottomOffset = topOffset + $(window).height() ;
      for(var n in nodes) {
        var node = nodes[n] ; 
        if(!node[0]._lazyloaded) {
          var nodeTop = node.offset().top ;
          if((nodeTop < bottomOffset) && (nodeTop + node.height() > topOffset)) {
            node[0]._lazyloaded = true ;
            func(nodes[n]) ;
          }
        }
      }
    } ;
    if(nodes.length > 0) {
      $(window).scroll(scrollFunc) ;
      scrollFunc() ;
    }
  } ;
})(jQuery) ;

The function lazyload() is implemented as a JQuery plugin, so it’s really easy to use. Whenever the elements, corresponding to the selector, appear in the window the function passed into lazyload() will be called with the JQuery element node as the function parameter. For example, to lazyload images into a document you could do something like this.

$(document).ready(function() {
  $("img[lazysrc]").lazyload(function(e) { e.attr("src",e.attr("lazysrc")) ; }) ;
}
...
<img width=500 height=400 lazysrc="big1.jpg"></img>
<img width=500 height=400 lazysrc="big2.jpg"></img>
<img width=500 height=400 lazysrc="big3.jpg"></img>
<img width=500 height=400 lazysrc="big4.jpg"></img>
...

I hope you find this usefull.

Advertisements

One Response to “Delayed loading of images and content using JQuery”

  1. pcfinch said

    I found this JQuery plugin, that is specifically for images, at http://www.appelsiini.net/projects/lazyload. It’s a lot more flexible if you are just dealing with images.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: