getButterfly Logo getButterfly code wrangling since 2005

We all know that an HTML page with more than 100 images will be relatively slow to load with no asset control. Loading images on a page is like unloading containers from a ship. It’s a nice analogy. If a bot or a crawler, or even a visitor hits this page, they will have to wait a while until the initial page render. I have found that the best solution for this is not lazy loading images, but deferring them altogether.


After the image is initialized, the lazy loading process can begin. My deferring approach is similar to lazy loading, but it renders all images automatically after page load. The trick is not to use a loop (such as each()) but to allow jQuery to use the DOM to generate everything.

I have a stress test on CodePen loading 999 images in a blink.

The low-down of the code is an <a> element:

<a href="#" data-defer-src=""></a>

and a bit of jQuery:

$(window).load(function() {
    $('a[data-defer-src]').prepend(function(index) {
        var src = $(this).data('defer-src');

        return '<img width="200" height="200" alt="" src="' + src + '" class="deferred">';

The jQuery bit can be improved to detect image size and to add various classes or IDs. It is a placeholder for a full fledged function or plugin.

The purpose of this code is to load a huge page with thousands of images in less than a second, then load each of them after the other page elements have been displayed. The code can be modified to accept a delay before starting to load images, or even a trigger, such as a button or an action.

Image source

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply

Love programming?

Learn about the most amazing things. Get smarter everyday!