Preloading Images With Jquery

Preloading images with jQuery

Quick and easy:

function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}

// Usage:

preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin:

$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

JQuery - Preload Images (using JQuery / native JavaScript / CSS)

You can preload an image quite easily as follows:

using JQuery

function preloadImg(src) {
$('<img/>')[0].src = src;
}

preloadImg('http://yoururl/to/the/picture.jpg');

or Native Javascript

function preloadImg(src) {
var img = new Image();
img.src = src;
}

preloadImg('http://yoururl/to/the/picture.jpg');

or Using CSS (no JavaScript required)

You can also preload images using CSS (and HTML)

CSS:
div#preload { display: none; }

HTML:

<div id="preload">
<img src="http://yoururl/to/the/picture1.jpg" width="1" height="1" alt="Image 1" />
<img src="http://yoururl/to/the/picture2.jpg" width="1" height="1" alt="Image 2" />
<img src="http://yoururl/to/the/picture3.jpg" width="1" height="1" alt="Image 3" />
</div>

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

Preloading set of images using jQuery

You should use a standard javascript for loop instead of the jQuery's foreach. Foreach is wonderful for looping over an array or set of objects, but not in this case. Here is an example, please note that you have to bind the onload event handler before you set the Image object's src property.

UPDATE: added more functions to complete the entire example.

var loaded_images = 0;
var frames = 400;
var images = [];

function preloadImages() {
for (i=0; i < frames; i++) {
images[i] = new Image();
images[i].onload = function() {
loaded_images += 1;
checkLoadingFinished();
}
images[i].src = 'frame-' + i + '.jpg';
}
}

function checkLoadingFinished() {
if (loaded_images >= frames) {
startAnimation();
}
}

function startAnimation() {
var frameNumber = 0;
var timer = setInterval(function() {
$('#img-dom-element').attr('src', images[frameNumber]);

if (frameNumber > frames) {
frameNumber = 0;
else
frameNumber++;

}, (1000/30)); // (1000/30) = 30 frames per second
}

$(document).ready(function() {
preloadImages();
});

Preload all images on a website with JQuery or Javascript

You could display a splash screen or a loading screen while the page is loading, and then remove this screen when JQuery tells you the page has been fully loaded. Something like this:

$(document).ready(function() {
// add loader
});

$(window).load(function() {
// remove loader
});

Javascript Preloading Images: Add to DOM, or not?

All browsers I've tested do load images even if they're not in the DOM. You can test this with https://jsfiddle.net/84tu2s9p/.

const img = new Image();
img.src = "https://picsum.photos/200/300";
img.onload = () => console.log("loaded");
img.onerror = err => console.error(err);
  • Safari 13, 11.1, 10.1
  • Edge 18
  • Firefox 72, 70, 62
  • Chrome 78, 71
  • Opera 64
  • IE11

(Not meant to be an exhaustive list. I just tried a variety of versions and browsers.)

There's also the new image.decode() API that is intended for this use case of preloading images and avoids potential dropped frames when actually decoding the image to render it. Edge doesn't support it yet (Chromium-based Edge will though).

Given that HTML Canvas can use images without them being in the DOM, I think they have to load images.



Related Topics



Leave a reply



Submit