40 Degree Day
40 Degree Day

Reputation: 2733

Load images from an array with jQuery

I have an array of numerical values and, using jQuery, would like to preload images based on that array. For example, if the array is ["1", "5", "8", "23"], I'd like to preload the following images:

/images/1.jpg
/images/5.jpg
/images/8.jpg
/images/23.jpg

What's the best way to accomplish this?

Upvotes: 1

Views: 2872

Answers (1)

Ahmet Kakıcı
Ahmet Kakıcı

Reputation: 6404

Source

var cache = [];
var imgArray=  new Array("1", "2", "3");
var prefix= "/images/";
var suffix = ".jpg";

function Preload(arrayName){
    var args_len = arrayName.length;
    for (var i = args_len; i--;) 
    {
        var cacheImage = document.createElement('img');
        cacheImage.src = prefix + arrayName[i] + suffix;
        cache.push(cacheImage);
    }
}

//usage
Preload(imgArray); 

Upvotes: 2

Related Questions