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

Preloading gallery images. JavaScript (without JQuery)

本文关键字:没有 JQuery JavaScript 加载 图像      更新时间:2023-09-26

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

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

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

帮助将不胜感激。

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

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

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

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
相关文章: