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 & lt; = $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');
});

This entry was posted in javascript, prototype. Bookmark the permalink.

12 Responses to Lazy Load Images with Prototype

  1. Mika Tuupola says:

    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

  2. Engin says:

    I couldnt make it work :/

  3. edd says:

    @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.

  4. holigan says:

    lazyload.js and prototype.js version 1.6.0_rc0

    I don’t use 2 above file. Who can help me, please?

  5. holigan says:

    can you detail guide for me using it?

    Thanks

  6. Alex says:

    Edd, would be interested in chatting with you about a version of this script that would work with images in a div set to overflow auto…

    Cheers.

  7. rahul says:

    I am new in jquery. I am not able add lazy load in my page. I am getting object does not support property or method error. Can u help me out?

  8. Pingback: 延迟加载图片(Lazy load images) « 付诸行动

  9. thomas says:

    do you have a working example of this as i am a new bee to java script and want to load my asp.net pages using your technique.

    Best Regards,

    Thomas

  10. Prototyper says:

    What do I need to change in the code to make it work with prototype 1.5.0 ?

  11. Is it possible to append an appear() (from scriptaculous) instead of just changing the src? if so, how?

  12. And btw, images are loaded in firefox 3.6 aswell when the page loads, and again when the page scrolls..

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>