Function to preload images?

一笑奈何 提交于 2019-12-02 09:24:14
["love-hover.jpg", "like-hover.jpg", "hate-hover.jpg"].forEach(function(img)
{
    new Image().src = "http://mypage.com/" + 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 = [
    "http://mypage.com/images/love-hover.png#",
    "http://mypage.com/images/love-hover2.png",
    "http://mypage.com/images/love-hover3.png"
];

And preload the images with a loop:

for (var i = 0; i < imageSrcs.lengthl i++)
    preloadImage(imageSrcs[i]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!