Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload images using jquery

Tags:

jquery

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?

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
    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'
]);

<

div>

like image 671
Hector Barbossa Avatar asked Dec 22 '10 06:12

Hector Barbossa


2 Answers

// 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'
]);
like image 100
Orson Avatar answered Oct 16 '22 13:10

Orson


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
});
like image 31
Christian Joudrey Avatar answered Oct 16 '22 12:10

Christian Joudrey