简体   繁体   English

在数组中预加载图像(并等待它们下载)

[英]Preloading images in an array (and waiting until they have downloaded)

So I came across another problem. 所以我遇到了另一个问题。

When I started redoing the webpage I am working on , I came across an idea - Why not have the page preload the materials, and while it's doing just that, show a loading screen? 当我开始重做我正在处理的网页时,我遇到了一个想法 - 为什么不让页面预加载材料,而它正在这样做,显示加载屏幕? Well, I made a function for that, but the thing is, it starts doing what it's supposed to, until it comes to the open() part of the image preloading. 好吧,我为此做了一个函数,但问题是,它开始做它应该做的事情,直到它来到图像预加载的open()部分。 It simply does not work. 它根本不起作用。 It is because I am giving it the arguments[i] part that is causing it to stop there? 这是因为我给它的论点[i]部分导致它停在那里? Is there a better way to do it? 有没有更好的方法呢?

function mainPageLoad() {
    var loadScreen = document.getElementById('pageload');
    loadScreen.innerHTML = "<p>Loading<span id='loadingWhat'>...</span></p><img src='images/loading.gif?v2'>";
    var loadspan = document.getElementById('loadingWhat');
    loadspan.innerHTML = " images";
    preloadImages(["images/logo.jpg"])
    //loadspan.innerHTML = " content";
    //preloadContent([""]);
}

function preloadImages() {
    var images = new Array();
    var imagesToLoad = arguments.length;
    document.writeln(imagesToLoad);
    var imagesLoaded = 0;
    document.writeln(imagesLoaded);
    for (i = 0; i < arguments.length; i++) {
        document.writeln("Loading images.");
        images[i] = new XMLHttpRequest();
        document.writeln("Made object");
        images[i].open("GET", arguments[i], true);
        document.writeln("Well, that worked.");
        images[i].send(null);
        document.writeln("Sent.");
        images[i].onreadystatechange = function() {
            document.writeln("Ready state change!");
            if (images[i].readystate == 4 && images[i].status == 200){
                imagesLoaded = imagesLoaded + 1;
                window.alertln("We have loaded another image.");
                window.alertln("Image" + String(imagesLoaded) + "out of" + String(imagesToLoad));           
            }
        }
    }
}

window.onload = init;

这是一种非常简单的预加载图像的方法,并在完成图像加载时调用回调,加载相关的先前问题/答案: 支持事件的图像预加载器javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM