Lazy Load Images with Prototype
Download lazyload.js.
Requires prototype.js version 1.6.0_rc0 or above.
Element.addMethods({ lazyload: function(element, options) { /** What does it do? It delays loading of images in (long) pages. Images below the fold (far down in the page) won’t be loaded before the user scrolls down. This is exact opposite of image preloading. With long pages containing heavy image content end user result is the same. Page feels snappier. Browser is in ready state after loading visible images. No need to wait for n pictures to load. From Wikipedia: Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. Inspired by: http://www.appelsiini.net/2007/9/lazy-load-images-jquery-plugin Requires: Prototype.js version 1.6.0_rc0 or later A page with lots of big images below the fold (optional) */ function $restore() { // this function restores the original image source; called when above the fold if ( true === $(element).hasAttribute('_src') ) { $(element).writeAttribute({ src: $(element).readAttribute('_src') }); } } function $scroll() { // this function returns the amount the page is scrolled vertically var scroll_y = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return parseInt(scroll_y); } function $height() { // this function returns the height of the viewport var window_height = window.innerHeight || document.documentElement.clientHeight; return parseInt(window_height); } var element = $(element); var options = Object.extend({ threshold : 0, placeholder : '/images/grey.gif', event : 'scroll', frequency : 0.1 }, options || {}); var offset = $(element).cumulativeOffset()[1]; var activate_on = (offset - options.threshold) - $height(); var old_source = $(element).readAttribute('src'); var new_source = options.placeholder; $(element) .writeAttribute({ src : new_source }) .writeAttribute({ '_src' : old_source }); if ( 'scroll' === options.event ) { new PeriodicalExecuter(function($executor) { if ( activate_on <= $scroll() ) { $restore(); $executor.stop(); } }, options.frequency); } else { $(element).observe(options.event, function(event) { $restore(); $(element).stopObserving(); }); } return $(element); } }); document.observe('contentloaded', function() { $$('img').invoke('lazyload'); });
September 7th, 2007 21:36
Nice work! If you find out a way around Safari bug which insist loading images anyway even though src has been changed/removed let me know.
http://bugs.webkit.org/show_bug.cgi?id=6656
March 30th, 2008 18:43
I couldnt make it work :/
April 10th, 2008 09:22
@Mike, it looks like this has been fixed in the latest webkit nightlies (it could have been fixed for a while).
@Engin, I have rewritted this a little to make it more stable. I’ll post it up today.