预加载图库图像。 JavaScript(没有JQuery)

时间:2016-02-21 23:56:52

标签: javascript image preloading

我正在试验一些要在图库中使用的大文件大小的图像。我试图以最简单的方式做到这一点。这里我只使用几个示例图像:

var imageGallery = ["nebula.jpg", "galaxy.jpg", "blackHole.jpg"];

for (var i = 0; i < imageGallery.length - 1; i++) {
    var img = new Image();
    img.src = imageGallery[i];
}

我知道这段代码可以确保图像在被脚本的其余部分使用之前被缓存,但它不起作用。

帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

你正在寻找某种异步回调,你必须做这样的事情:

// Grab reference to image on page
var img = document.getElementById("blah");  // Or whatever you need to do

// Create new image from your list
var galleryImage = new Image();

// Create a callback that will start once you assign the src attribute to img 
galleryImage.onload = function() {

    // Here you could disable a loading icon or something, because your image is ready to go
    img.src = this.src;
}

// Kickoff everything
galleryImage.src = "www.myimage.com/path";

在您的代码中可能看起来像这样:

var imageGallery = ["nebula.jpg", "galaxy.jpg", "blackHole.jpg"];

for (var i = 0; i < imageGallery.length - 1; i++) {
    var img = document.document.getElementsByTagName('img')[i];
    var galleryImage = new Image();

    galleryImage.onload = function() {
        img.src = this.src;
    }

    galleryImage.src = imageGallery[i];
}

答案 1 :(得分:0)

也许服务器正在发送阻止缓存的标头,例如:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0