0

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.

2
  • What part is not working exactly? Commented Feb 22, 2016 at 0:00
  • When I open the page after clearing the cache, the first image starts loading immediately, row by row from the top down, then other images load too quickly. Once everything has loaded the slideshow runs normally - but it's a mess in the beginning. Commented Feb 22, 2016 at 1:03

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. is it a ok to make a function in a loop like that?
There are certainly a lot of times where you wouldn't want to put an async function inside a loop like that, but in this case it will be fine.
0

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

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

2 Comments

Thanks.That would be odd. Is there anything else I can do to make sure that when I want to display these images they are ready?
@Jason210 there's also the onload function that can help you making sure they are all loaded, take a look at this answer: stackoverflow.com/questions/12354865/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.