javascript - Function to preload images? - Stack Overflow

I'm successfully pre-loading an image on my website with this JavaScript:loveHover = new Image();

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

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

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;
}

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

loveHover = new Image();
loveHover.src = "http://mypage./images/love-hover.png";

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 = "http://mypage./images/";
    image.src = path + image;
}
Share Improve this question edited Jan 9, 2013 at 18:05 KatieK 13.9k19 gold badges78 silver badges91 bronze badges asked Mar 8, 2011 at 16:09 mattmatt 44.5k107 gold badges268 silver badges402 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 3
["love-hover.jpg", "like-hover.jpg", "hate-hover.jpg"].forEach(function(img)
{
    new Image().src = "http://mypage./" + 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./images/love-hover.png#",
    "http://mypage./images/love-hover2.png",
    "http://mypage./images/love-hover3.png"
];

And preload the images with a loop:

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

Have you tried not using javascript at all?

http://perishablepress./press/2008/06/14/a-way-to-preload-images-without-javascript-that-is-so-much-better/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745620416a4636483.html

相关推荐

  • javascript - Function to preload images? - Stack Overflow

    I'm successfully pre-loading an image on my website with this JavaScript:loveHover = new Image();

    9小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信