Jason210
Jason210

Reputation: 3350

Preloading gallery images. JavaScript (without JQuery)

I was experimenting with some images of large file sizes to be used in a gallery. I'm trying to do this in the most simple way possible. Here I am using just a few example images:

var imageGallery = ["nebula.jpg", "galaxy.jpg", "blackHole.jpg"];

for (var i = 0; i < imageGallery.length - 1; i++) {
    var img = new Image();
    img.src = imageGallery[i];
}

I understood that this code would make sure the images are cached before being used by the rest of the script, but it's not working.

Help would be appreciated.

Upvotes: 0

Views: 150

Answers (2)

Tyler
Tyler

Reputation: 18177

You're looking for some sort of async callback, you'll have to do something like this:

// Grab reference to image on page
var img = document.getElementById("blah");  // Or whatever you need to do

// Create new image from your list
var galleryImage = new Image();

// Create a callback that will start once you assign the src attribute to img 
galleryImage.onload = function() {

    // Here you could disable a loading icon or something, because your image is ready to go
    img.src = this.src;
}

// Kickoff everything
galleryImage.src = "www.myimage.com/path";

In your code that might look something like this:

var imageGallery = ["nebula.jpg", "galaxy.jpg", "blackHole.jpg"];

for (var i = 0; i < imageGallery.length - 1; i++) {
    var img = document.document.getElementsByTagName('img')[i];
    var galleryImage = new Image();

    galleryImage.onload = function() {
        img.src = this.src;
    }

    galleryImage.src = imageGallery[i];
}

Upvotes: 1

Rodrigo Gra&#231;a
Rodrigo Gra&#231;a

Reputation: 2165

Maybe the server is sending headers that prevent caching, like:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

Upvotes: 0

Related Questions