Prevent images from loading

If you render the HTML on the page, even if it's hidden, it's going to load. If you want images to load only when they're needed, you're going to have to dynamically set the source (src) on the image tag in javascript.

Edit 1: The script you referenced merely checks to see how far you've scrolled the page down and then determines which images are visible (or almost visible) by checking their top -- see the $.belowthefold and $.rightoffold extensions.

The example works great when the images are all the same size because their containers can also be the same size and you won't get any odd page resizing behavior when you lazy load them. If your images' heights and widths vary, you may get some odd results.  

Edit 2:

<script type="text/javascript" charset="utf-8">
    $(document).ready( function() { $("img").removeAttr("src"); } );
</script>

<img src="Chrysanthemum.jpg" />
<img src="Desert.jpg" />
<img src="Hydrangeas.jpg" />
<img src="Jellyfish.jpg" />
<img src="Koala.jpg" />
<img src="Lighthouse.jpg" />
<img src="Penguins.jpg" />
<img src="Tulips.jpg" />

You can wrap the image in a noscript tag:

<noscript>
<img src="foo.jpg"/>
</noscript>

All browsers that has JavaScript enabled will ignore the image tag so the image won't load.


Store the URLs somewhere else, then set all image URLs to some dummy image (empty, transparent, "loading data...", whatever). When an image should be displayed, use JS to set the src attribute and the browser will fetch it.


Well with Prototype you can do something like this I guess:

var unloaded = [];
$$('img.noload').each(function (image) {
    unloaded.push(image);
    image._src = image.src;
    image.src = '';
});

To load all of them:

unloaded.each(function (image) {
    image.src = image._src;
});

To load the first one:

function loadImage (image) {
    image.src = image._src;
}

loadImage(unloaded.shift());

Well I hope you got the idea.

Tags:

Javascript