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?



<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 /;
        // ...
    } 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 =;
    var s = document.createElement("script");
    s.innerHTML = e.responseText;
    // or: s[s.innerText!=undefined?"innerText":"textContent"] = e.responseText

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

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).


You might like to have a look at How to show loading status in percentage for ajax response?

It is to see the status of an AJAX download. Since you are loading a script, it might not be the best way to get the file but it could work. You would then need to put the content received by the ajax call somewhere to execute, and eval is not recommended.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.