Preloading images with JavaScript & jQuery
I am using the following code to insert some HTML in a div and to preload any images that may be contained in that HTML (the html var data is actually retrieved from the AJAX request in real code). This is to prevent the browser from loading the extracted HTML images by showing the div (using the slideDown event) because it breaks the flow when the image is loaded from the middle of the transition. I guess I could use interlaced JPEG so that the image dimensions are known almost immediately, but obviously it would be nice to develop a cleaner method.: P
var html = '<img src="images/test.jpg" alt="test" />';
$('div.content').hide().html(html);
$('div.content img').each(function(){
var img = new Image();
img.src = $(this).attr('src');
$(this).attr('src', img.src);
});
$('div.content').slideDown('normal');
I'm using the Image object and then assigning it as recommended here , but unfortunately the image is still not cached by the browser using this method because the sildeDown () effect still breaks as the image loads.
Any help or alternative methods? Many thanks.
Edit - 21 Sep 09
Progress! It turns out the browser was caching the image, I just didn't give it time to do it (it just took a second to load with alert () or setInterval ()). Now, imagining what is arguably the most messy code - I'm using an infinite loop to create that pause.
The new method extends the old code above by binding a function (which adds each src image to an array) to this successful image load event. Then it gets stuck in an infinite loop while it waits for all the images to load and hence appear in the array. This seems to work as a way to preload images synchronously, but the problem remains; the while () loop loops endlessly for whatever reason even after all images have loaded, unless I add an alert () to pause it for a moment.
New code:
var html = '<img src="images/test.jpg" alt="test" />';
$('div.content').hide().html(html);
// define usr variables object
$.usrvar = {};
// array of loaded images' urls
$.usrvar.images = [];
// boolean for whether this content has images (and if we should check they are all loaded later)
$.usrvar.hasimages = false;
// foreach of any images inside the content
$('div.content img').each(function(){
// if we're here then this content has images..
$.usrvar.hasimages = true;
// set this image src to a var
var src = $(this).attr('src');
// add this image to our images array once it has finished loading
$(this).load(function(){
$.usrvar.images.push(src);
});
// create a new image
var img = new Image();
// set our new image src
img.src = src;
});
// avoid this code if we don't have images in the content
if ($.usrvar.hasimages != false) {
// no images are yet loaded
$.usrvar.imagesloaded = false;
// repeatedly cycle (while() loop) through all images in content (each() loop)
while ($.usrvar.imagesloaded != true) {
$('div.content img').each(function(){
// get this loop image src
var src = $(this).attr('src');
// if this src is in our images array, it must have finished loading
if ($.usrvar.images.indexOf(src) != -1) {
// set imagesloaded to trueai
$.usrvar.imagesloaded = true;
} else {
// without the pause caused by this alert(), this loop becomes infinite?!
alert('pause');
// this image is not yet loaded, so set var to false to initiate another loop
// (ignores whether imagesloaded has been set to true by another image, because ALL
// need to be loaded
$.usrvar.imagesloaded = false;
}
});
}
}
$('div.content').slideDown('normal');
source to share
I made the following solution, but it hasn't been tested, so you'll be warned;)
// HTML (any formatting possible)
// no src for the images: it is provided in alt which is of the form url::actualAlt
var html = "<p><img alt='images/test.jpg::test' /><br />Some Text<br /><img alt='images/test2.jpg::test2' /></p>";
$(document).ready(function() {
// Reference to the content div (faster)
var divContent = $("div.content");
// Hide the div, put the HTML
divContent.hide().html(html);
// Webkit browsers sometimes do not parse immediately
// The setTimeout(function,1) gives them time to do so
setTimeout(function() {
// Get the images
var images = $("img",divContent);
// Find the number of images for synchronization purpose
var counter = images.length;
// Synchronizer
// will show the div when all images have been loaded
function imageLoaded() {
if (--counter<=0) $('div.content').slideDown('normal');
}
// Loading loop
// For each image in divContent
$.each(images,function() {
// Get the url & alt info from the alt attribute
var tmp = $(this).attr("alt").split("::");
// Set the alt attribute to its actual value
$(this).attr("alt",tmp[1]);
// Wire the onload & onerror handlers
this.onload = this.onerror = imageLoaded;
// Set the image src
this.src = tmp[0];
});
},1);
});
source to share
I played around with this and I created a slightly different solution. Instead of pushing images to an array as they load, you push them all to an array in a loop, and then in the load event, you remove them from the array and call the "finished" function. It checks if the image array is free and then it cleans up and shows the content.
var html = '< animg src="images/test.jpg" alt="test" />'; // not allowed to post images...
$('div.content').hide().html(html);
// preload images
// define usr variables object
$.usrvar = {};
// array of loaded images' urls
$.usrvar.images = [];
// initially no images
$.usrvar.hasimages = false;
$('div.content img').each(function() {
// if we're here then this content has images..
$.usrvar.hasimages = true;
// set this image src to a var
var src = this.src;
// add this image to our images array
$.usrvar.images.push(src);
// callback when image has finished loading
$(this).load(function(){
var index = $.usrvar.images.indexOf(src);
$.usrvar.images.splice(index,1);
finish_loading();
});
// create a new image
var img = new Image();
// set our new image src
img.src = src;
});
if(!$.usrvar.hasimages) finish_loading();
function finish_loading() {
if($.usrvar.hasimages) {
if($.usrvar.images.length > 0) return;
}
$('div.content').slideDown('normal');
}
Edit: Looking at Julien's post, his method is better. My method works in a similar way, but like the original solution, it tracks the images using the srcs array, rather than just counting (which is more efficient).
Edit 2: Ok, I thought this was the best solution, but it doesn't seem to work for me. Maybe something to do with a load event triggered too close to each other. Sometimes it works, but sometimes it freezes while loading images and the image counter never reaches zero. I went back to the method in my post above.
Edit 3: It looks like a setTimeout issue was causing this.
source to share
This is what I am using. As you can see from my points, I am not a pro, but I found this somewhere and it works great for me and seems much simpler than anything posted. I may have missed this requirement. :)
var myImgs = ['images/nav/img1.png', 'images/nav/img2.png', 'images/nav/img3.png', 'images/nav/img4.png', 'images/expand.png', 'images/collapse.png'];
function preload(imgs) {
var img;
for (var i = 0, len = imgs.length; i < len; ++i) {
img = new Image();
img.src = imgs[i];
}
}
preload(myImgs);
source to share