What is the easiest way to preloading images in JavaScript ?
Quick and easy:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively we could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.png',
'img/anotherOne.png',
'img/image1.png'
]);
Copy Code We need a jQuery plugin:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.png','img2.png','img3.png']).preload();
Copy Code
An images loading into DOM and hides it by default.
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
Copy Code In JavaScript using Image object.
To trigger a callback upon loading all images. We will never trigger a callback it will happens to at least one resource is not loaded.
var preloadPictures = function(pictureUrls, callback) {
var i,
j,
loaded = 0;
for (we = 0, j = pictureUrls.length; we < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback();
}
};
// Use the following callback methods to debug
// in case of an unexpected behavior.
img.onerror = function () {};
img.onabort = function () {};
img.src = src;
} (new Image(), pictureUrls[i]));
}
};
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('a');
});
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('b');
});
Copy Code
Some solution they are given the images are before moving along with loading the page. That problem to be overcome by implemented in the following solution. Basically we added a callback in jQuery preload plugin, after that the images are properly loaded.
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var we = 0; we < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
Copy Code Given an other solution for this problem to refer and use it:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
Copy Code
This problem overcome the images are preloading on Ajax calls.
Using jQuery code to creates (and loads) from DOM element img without showing it:
$('<img src="img/1.jpg"/>');
Copy Code