Function to preload images?

前端 未结 3 393
北海茫月
北海茫月 2021-01-26 02:02

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

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


        
相关标签:
3条回答
  • 2021-01-26 02:12

    Have you tried not using javascript at all?

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

    0 讨论(0)
  • 2021-01-26 02:28
    ["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.

    0 讨论(0)
  • 2021-01-26 02:28

    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]);
    
    0 讨论(0)
提交回复
热议问题