Mental Jetsam

By Peter Finch

Archive for August, 2010

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.

Posted in JQuery | 1 Comment »