Search code examples
javascriptjqueryhtmlcssimage-preloader

Pre Load images to display later on click event jQuery


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.


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.