Nick Clark Nick Clark - 5 months ago 23
jQuery Question

Lazy loading images

I'm looking for a JQuery plugin that supports lazy loading images. The Lazy Load JQuery plugin is no longer supported and does not work in Firefox.

Does anyone know a good alternative that supports most modern browsers?

I'm also open to other approaches. I have a hidden div with images that I don't want to load unless the div is made visible. Let me know if there are better approaches to deferring the image load in this situation.

Answer

I encountered a similar situation in a tab style page where the content in initially invisible tabs was downloading unnecessarily. The solution I went with was to create markup like:

<img src="#" data-src="/img/foo.png"/>

and then in the javascript that handles the tab transitions I also substituted the "data-src" attribute into the "src" attribute of those images.

$thisTab.find('img[data-src]').each(function(img) {
    var $img = $(img);
    $img.attr('src', $img.attr('data-src'))
        .removeAttr('data-src');
});

This accomplishes the goal of only loading the images when the tab is selected, and is valid html5!

Comments