The Definitive Best Way to Preload Images Using JavaScript/Jquery

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

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).

What is the best way to preload multiple images in JavaScript?

EDIT:

Actually, I just put it to the test, and Method A does not work as intended:

Check it out: http://www.rootspot.com/stackoverflow/preload.php

If you click on the 2nd image when the page is finished loading, it should appear instantaneously because it was preloaded, but the first one doesn't because it didn't have time to load before the source was changed. Interesting. With this new development, I'd just go ahead and use Method C.

Preload Image With JavaScript

as you tagged javascript, here is my answer:

I would prefer

<script>
var preloadImg = new Image(266, 266);
preloadImg.src = 'http://via.placeholder.com/266x266';
</script>

as then you can later use the preloadImg variable, whereas if you did it with html, you would have to go through unnecessary steps to cache the image into a javascript variable

uses of this for example might be drawing on a canvas, and there are many more - javascript is awesome

However, one tiny reason (which should not be accepted) to use the html preloading is for browsers without javascript, or with javascript disabled, as the option is pure html

Hope this helps (I prefer the javascript method)

Preloading a large number of images

Have a look at ImageLoader.

You can use it to load images and keep track of the loaded images.
e.g.

var imageLoader1 = new ImageLoader( {
"images": [
{ "id":101, file: "path/image1.png" },
{ "id":102, file: "path/image2.png" }
],
"onAllLoaded":function() { alert( "Images loaded" ); }
} );

This is if you want to pre-load all the images. For 600 images, probably you shouldn't do this though.

Pre-load Next Image jQuery

var newImageUrl = 'someimage.png';

/* preload an image using jQuery: */
$('<img>').attr( {
src: newImageUrl
} ).load(function() {
/* image is loaded and could be used */
} );

How would I (or should I) extend Modernizr.load() to preload images?

On the yepnope documentation, it is specified that the preload! prefix "should" work on some other mime types.

You can try

Modernizr.load('preload!something/image1.jpg');

This work for me.

Don't forget to add the prefix plugin (else you will get an error when the js engine tries to execute the image) :

yepnope.addPrefix( 'preload', function ( resource ) {
resource.noexec = true;
return resource;
});

Preload Images with javascript

You need to send an Expires header with the image from the server to enable caching in the browser.

e.g. in Apache (in .htaccess)

enable expires:

ExpiresActive On

by date:

ExpiresDefault "access plus 30 days"

or by filetype:

ExpiresByType image/gif "modification plus 5 hours 3 minutes"

jquery hidden preload

Why not just set the css display property to none, and change it with JS when the document has loaded? If you're using jQuery on your page, it could look like this:

CSS:

#mydiv { display: none; }

JavaScript:

$(document).ready(function() {
$('#mydiv').show();
});


Related Topics



Leave a reply



Submit