简体   繁体   中英

Javascript download progress in script tag

Is there any convinient solution to watch a download progress of my huge javascript library files that written inside <script src="/js/hugelib.js"></script> tag?

Obvious, $.ajax() progress bar is not usefull. in headjs project I can to find setup progress settings, jsut ready() .

You could issue a GET using XMLHttpRequest, resulting in it getting cached in the browser, then use JavaScript to add the tag to the document, making it load near instantly.

var req = new XMLHttpRequest(); 
req.onprogress=myUpdateProgressFunction; // whatever you want to do!
req.open('GET', '/js/hugelib.js', true);  
req.onreadystatechange = function (aEvt) {  
    if (req.readyState == 4) 
    {  
        var hugeScript = document.createElement('script');
        hugeScript.setAttribute('src','/js/hugelib.js');
        document.head.appendChild(hugeScript);
    }  
};  
req.send(); 

You could also consider just setting the hugeScript.text with the results of the AJAX GET, but I'm fairly sure that would perform poorly.

As a further refinement, you could issue a HEAD request first to see if the item is already cached, if it is, don't attempt the AJAX GET. Again, you'd have to profile performance to see if that actually improves performance or not overall.

NB: I haven't tested the behaviour of this pattern, I'm taking it in good faith that the browser cache will act in a gentlemanly fashion.

Options that come to my mind:

  • Using a small js code to create a progress bar and then loading your code dynamically (by a XHR) . I see here two problems: you need to do some tricks to know the progress and you are adding more code to be loaded, but the first one can be solved and the second one... well, a few lines more won't affect much. An already created code to do this would be PreloadJS , one of the modules of CreateJS
  • Using minify or any similar tool to minimize the size of your code. You can save a surprising amount of bytes using these tools.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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