简体   繁体   中英

How to preload an image using jQuery

Hi I have a project in which one of the pages has a gallery. Something like that:

 <div id="gallery" class="sections">
        <img src="Images/Image1.jpg" class="thumbnails">
        <img src="Images/Image2.jpg" class="thumbnails">
        <img src="Images/Image3.jpg" class="thumbnails">
        etc...
 </div>

I would like to preload these images so that when you access the gallery page they are already loaded. I know you can do this by using javascript. Something along the lines of:

var myImage = new Image();
myImage1.src = "Images/Image1.jpg";
etc...

What I am unsure about is the next step. Do I remove the src from the html and add an id, like so:

 <div id="gallery" class="sections">
        <img id="image1" class="thumbnails">
        <img id="image2" class="thumbnails">
        <img id="image3" class="thumbnails">
        etc...
 </div>

and then do something like that:

$('#image1').append(myImage1);

This hasn't worked... I have also tried:

$('#image1').attr('src','Images/Image1.jpg');

And that hasn't worked either.

I have had a look around and there are plenty of tutorials about how to make a function that preloads your images etc... but I am not quite there yet. I just would like to know how to do it on a one by one basis for now and then maybe create a function. Thanks.

They are many function to do that Images are loaded in the DOM when the page is open, but not visibles. Then, when you want show them (On click, on a slider, ...), no load time !

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Use your function with all your image path

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM