Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

javascript - How can I get the progress of a downloading <script>?

Let's say, for example, I'm creating a game. I have a small script whose job is to load all the assets and present a progress bar to the user while the assets load.

One such asset is a rather large script which contains the game logic. Perhaps upwards of 3 MB.

How can I show the loading progress of the second script to the user?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

<script> tags only fire load and error events; they do not fire progress events. However, in modern browsers, Ajax requests do support progress events. You can load your script content and monitor progress through Ajax, and then place the script contents into a new <script> element when the load completes:

var req = new XMLHttpRequest();

// report progress events
req.addEventListener("progress", function(event) {
    if (event.lengthComputable) {
        var percentComplete = event.loaded / event.total;
        // ...
    } else {
        // Unable to compute progress information since the total size is unknown
    }
}, false);

// load responseText into a new script element
req.addEventListener("load", function(event) {
    var e = event.target;
    var s = document.createElement("script");
    s.innerHTML = e.responseText;
    // or: s[s.innerText!=undefined?"innerText":"textContent"] = e.responseText
    document.documentElement.appendChild(s);

    s.addEventListener("load", function() {
        // this runs after the new script has been executed...
    });
}, false);

req.open("GET", "foo.js");
req.send();

For older browsers that don't support Ajax progress, you can build your progress-reporting UI to show a loading bar only after the first progress event (or otherwise, show a generic spinner if no progress events ever fire).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...