Question

I have a web page where lots of images called from server using image scr attribute.

I have created a function like which is triggered by td click.

function GoToStep(stepNo) {
 var imgSrc = $("#h1" + stepNo).val();
        $(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}

Now the problem is this. For slower connections the images come after some moment.

Can I pre load images to avoid waiting time when user clicks td?

I have seen some jquery function to pre load images.

Kindly give some idea how can I achieve it.

Was it helpful?

Solution

Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:

<img src="image.png" alt="" style="display:none;"/>

Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.

OTHER TIPS

This can be done using some javascript functions. Quoting from another question.

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'
]);

Explanation of how javascript preloaders work (different question)

[...] The way it works is simply by creating a new Image object and setting the src of it, the browser is going to go grab the image. We're not adding this particular image to the browser, but when the time comes to show the image in the page via whatever method we have setup, the browser will already have it in its cache and will not go fetch it again. [...]

So in your case, you should use something like

$(function() {
    // Do stuff when DOM is ready
    preload([
        'img/bg1.jpg',
        'img/bg2.jpg',
        'img/bg3.jpg'
    ]);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top