Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The definitive best way to preload images using JavaScript/jQuery?

I'm fully aware that this question has been asked and answered everywhere, both on SO and off. However, every time there seems to be a different answer, e.g. this, this and that.

I don't care whether it's using jQuery or not - what's important is that it works, and is cross-browser.]

So, what is the best way to preload images?

like image 762
Skilldrick Avatar asked May 23 '09 15:05

Skilldrick


People also ask

Can you preload images?

Starting in Chrome 73, the browser can preload the right variant of responsive images specified in srcset before it discovers the img tag! Depending on your site's structure, that could mean significantly faster image display!

What is Preloader IMG?

"Preloading" loads an image file into the users' computer memory so that it can be instantly accessed when needed. This is useful, for example, if you have a mouseover event and an image needs to change without any delay.


4 Answers

Unfortunately, that depends on your purpose. If you plan to use the images for purposes of style, your best bet is to use sprites. http://www.alistapart.com/articles/sprites2

However, if you plan to use the images in <img> tags, then you'll want to pre-load them with

function preload(sources)
{
  var images = [];
  for (i = 0, length = sources.length; i < length; ++i) {
    images[i] = new Image();
    images[i].src = sources[i];
  }
}

(modified source taken from What is the best way to preload multiple images in JavaScript?)

using new Image() does not involve the expense of using DOM methods but a new request for the image specified will be added to the queue. As the image is, at this point, not actually added to the page, there is no re-rendering involved. I would recommend, however, adding this to the end of your page (as all of your scripts should be, when possible) to prevent it from holding up more critical elements.

Edit: Edited to reflect comment quite correctly pointing out that separate Image objects are required to work properly. Thanks, and my bad for not checking it more closely.

Edit2: edited to make the reusability more obvious

Edit 3 (3 years later):

Due to changes in how browsers handle non-visible images (display:none or, as in this answer, never appended to the document) a new approach to pre-loading is preferred.

You can use an Ajax request to force early retrieval of images. Using jQuery, for example:

jQuery.get(source);

Or in the context of our previous example, you could do:

function preload(sources)
{
  jQuery.each(sources, function(i,source) { jQuery.get(source); });
}

Note that this doesn't apply to the case of sprites which are fine as-is. This is just for things like photo galleries or sliders/carousels with images where the images aren't loading because they are not visible initially.

Also note that this method does not work for IE (ajax is normally not used to retrieve image data).

like image 79
Jonathan Fingland Avatar answered Oct 16 '22 12:10

Jonathan Fingland


Spriting

As others have mentioned, spriting works quite well for a variety of reasons, however, it's not as good as its made out to be.

  • On the upside, you end up making only one HTTP request for your images. YMMV though.
  • On the down side you are loading everything in one HTTP request. Since most current browsers are limited to 2 concurrent connections the image request can block other requests. Hence YMMV and something like your menu background might not render for a bit.
  • Multiple images share the same color palette so there is some saving but this is not always the case and even so it's negligible.
  • Compression is improved because there is more shared data between images.

Dealing with irregular shapes is tricky though. Combining all new images into the new one is another annoyance.

Low jack approach using <img> tags

If you are looking for the most definitive solution then you should go with the low-jack approach which I still prefer. Create <img> links to the images at the end of your document and set the width and height to 1x1 pixel and additionally put them in a hidden div. If they are at the end of the page, they will be loaded after other content.

like image 40
aleemb Avatar answered Oct 16 '22 12:10

aleemb


As of January 2013 none of the methods described here worked for me, so here's what did instead, tested and working with Chrome 25 and Firefox 18. Uses jQuery and this plugin to work around the load event quirks:

function preload(sources, callback) {
    if(sources.length) {
        var preloaderDiv = $('<div style="display: none;"></div>').prependTo(document.body);

        $.each(sources, function(i,source) {
            $("<img/>").attr("src", source).appendTo(preloaderDiv);

            if(i == (sources.length-1)) {
                $(preloaderDiv).imagesLoaded(function() {
                    $(this).remove();
                    if(callback) callback();
                });
            }
        });
    } else {
        if(callback) callback();
    }
}

Usage:

preload(['/img/a.png', '/img/b.png', '/img/c.png'], function() { 
    console.log("done"); 
});

Note that you'll get mixed results if the cache is disabled, which it is by default on Chrome when the developer tools are open, so keep that in mind.

like image 6
Mahn Avatar answered Oct 16 '22 13:10

Mahn


In my opinion, using Multipart XMLHttpRequest introduced by some libraries will be a preferred solution in the following years. However IE < v8, still don't support data:uri (even IE8 has limited support, allowing up to 32kb). Here is an implementation of parallel image preloading - http://code.google.com/p/core-framework/wiki/ImagePreloading , it's bundled in framework but still worth taking a look.

like image 3
Angel Avatar answered Oct 16 '22 13:10

Angel