In my web page some images are taking a lot of time to load in IE.So I used this for preloading images in my page.But still the problem persists.Any suggestions?
// Create an image element
var image1 = $('<img />').attr('src', 'imageURL.jpg');
// Insert preloaded image into the DOM tree
$('.profile').append(image1);
// OR
image1.appendTo('.profile');
But the best way is to use a callback function, so it inserts the preloaded image into the application when it has completed loading. To achieve this simply use .load() jQuery event.
// Insert preloaded image after it finishes loading
$('<img />')
.attr('src', 'imageURL.jpg')
.load(function(){
$('.profile').append( $(this) );
// Your other custom code
});
Update #1
function preload(arrayOfImages) {
$(arrayOfImages).each(function(index){
$('<img />')
.attr('src', arrayOfImages[index])
.load(function(){
$('div').append( $(this) );
// Your other custom code
});
});
alert("Done Preloading...");
}
// Usage:
preload([
'/images/UI_1.gif',
'/images/UI_2.gif',
'/images/UI_3.gif',
'/images/UI_4.gif',
'/images/UI_5gif',
'/images/UI_6.gif',
'/images/UI_7.gif',
'/images/UI_8.gif',
'/images/UI_9.gif'
]);
Images sprites can speed things up tremendously (but make sure you compress them using something like ImageOptim). Next, host all your images on a CDN somewhere (I suggest Amazon S3/CloudFront). And lastly, preload all your images using something like below, and try and call this as early as possible. Hopefully this helps!
function loadImages(){
var images = [
'http://cdn.yourdomain.com/img/image1.png',
'http://cdn.yourdomain.com/img/image2.jpg',
'http://cdn.yourdomain.com/img/image3.jpg',
'http://cdn.yourdomain.com/img/image4.jpg'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
}
Try out this jQuery plugin: http://farinspace.com/jquery-image-preload-plugin/
It allows you to grab img
elements using a selector and have it preload them. I'm not sure if the images you want to preload are already in the HTML, if they are you might be interested by this plugin as it allows you to do:
$('#content img').imgpreload(function()
{
// this = jQuery image object selection
// callback executes when all images are loaded
});
While still allowing you to manually preload images with file names:
$.imgpreload('/images/a.gif',function()
{
// this = new image object
// callback
});