Nick
Nick

Reputation: 171

Javascript not caching images

I have a gif that i made in phototshop (a loading wheel) but i find that the way that i am using it (hiding and then displaying with css and over writing with javascript later on) is just too laggy to begin with, it really skips hard at the beginning. so i decided to cache the image before i call it. so this is how i did it:

function preloadImages(array) {
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.src = array[i];
        preloadImages.list.push(img);
    } 
}

var imageURLs = [
    "loading.gif"
];

Which should work, if im not mistaken. But just in case i have also tried:

loading = new Image(60,60)
loading.src = "images/loading.gif"

which i pulled from a tutorial. Now when I implement this(currently the first one) and then call the image normally later on, it seemingly runs faster and i can see it in my cache. however being the skeptic i am i decided to put in an image that i never use in the HTML and see if it gets cached(as it should) but then never call it. so heres my new JS:

function preloadImages(array) {
    for (var i = 0; i < array.length; i++) {
        var img = new Image();
        img.src = array[i];
        preloadImages.list.push(img);
    } 
}

var imageURLs = [
    "loading.gif",
    "today.gif"
];

Notice i added in today.gif Now, if my understanding of caching is correct, this image should now be cached even though i never call it in my "raw" HTML correct? well its not. which makes me wonder if the loading gif was even cached or if my browser just decided to cooperate for a bit. any ideas? heres what the cache look like on reload after a fresh clear with the second javascript snippet in use:

cache

so the questions here are: Is it working even though the cache says it's not? Am i imagining things? Am i doing this correct/is my understanding of local cache correct? If not, could someone explain to me where im going wrong? cheers.

Upvotes: 0

Views: 149

Answers (2)

HellaMad
HellaMad

Reputation: 5374

The function you define expects an array as an argument.

Try preloadImages(["images/loading.gif", "images/today.gif"]);. Currently you're missing closing quotes and not passing an array, but rather two separate strings as arguments.

Upvotes: 1

spaceman12
spaceman12

Reputation: 1109

Your doing it incorrectly -

When creating image object inside your for loop, do it within a closure function or the previous object will gets overwritten by the last one, the nature of its being asynchronouse -

(function(i){
var img = new Image();
img.src= array[i];}(i))

also, your creating a list and pushing the object to it is totally useless!

Upvotes: 0

Related Questions