Delay image loading with jQuery

2013-04-15

This is a quick javascript tip if you want to delay the loading of certain images until an event is triggered, for example onLoad on Window. An image is not loaded if it doesn’t have the src attribute set. So simply set the image source as a temporary attribute like in this example:

<img src="" alt="" data-src="bild.jpg">

And when an event is triggered, set the image elements src to the temporary source.

$(window).load(function(){
    $('.js-delayLoad').each(function(){
        this.src = $(this).data('src');
    });
});

Could be useful if you want to delay the loading of large images for lightboxes and don’t want them to be loaded from start.