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.

Jason210
  • 2,990
  • 2
  • 17
  • 18
  • What part is not working exactly? – Larry Lane Feb 22 '16 at 00: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. – Jason210 Feb 22 '16 at 01:03

2 Answers2

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];
}
Tyler
  • 17,669
  • 10
  • 51
  • 89
  • Thanks. is it a ok to make a function in a loop like that? – Jason210 Feb 22 '16 at 00:59
  • 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. – Tyler Feb 22 '16 at 01:12
0

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

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
Rodrigo Graça
  • 1,985
  • 3
  • 17
  • 24
  • 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 Feb 22 '16 at 00:05
  • @Jason210 there's also the onload function that can help you making sure they are all loaded, take a look at this answer: http://stackoverflow.com/questions/12354865/image-onload-event-and-browser-cache – Rodrigo Graça Feb 22 '16 at 00:17