Function to preload images?

I'm successfully pre-loading an image on my website with this JavaScript:

loveHover = new Image();
loveHover.src = "";

Is there an easy an good way to pack this thing into a function? Something like:

function preloadImage(image) {
    var image = new Image();
    var path = "";
    image.src = path + image;


["love-hover.jpg", "like-hover.jpg", "hate-hover.jpg"].forEach(function(img)
    new Image().src = "" + img;

To get this to work in IE versions earlier than 9, see the Array.forEach Compatibility section for instructions.


Well the unique part of the function would be the src (link to image). So make that the argument.

function preloadImage(src) {
    var image = new Image();
    image.src = src;

Then if you have multiple urls store them in an array:

var imageSrcs = [

And preload the images with a loop:

for (var i = 0; i < imageSrcs.lengthl i++)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.