简体   繁体   中英

How to block if JS download is not completed

I am downloading the JS file asynchronously by appending the JS file to HTML head. Now in html body, before using the JS file, I want to check if JS file has downloaded and is present in the cache. If the JS file is NOT present in the cache(eg: in case of slow internet connnections), I want to block until it is downloaded. In other words, if JS download is not complete, i want to simulate the behavior as in the case of blocking JS download.

Any idea how this can be achieved?

您可以实例化JS文件中的任何对象,并且可以在HTML文件中使用typeOf运算符检查该对象是否可用,因此,如果typeof(x)未定义,则可以假定该文件尚未下载

If you have control over the HTMl file and the JS file: define a "callback" function somewhere in the already-loaded code, and call it from the end of your JS file. Example function:

<html>
  <head>
  <script>
    function notify_file_is_loaded(identifier) {
      if (identifier === 'somefile.js') {
        // it's loaded!
        // run the code that (in synchronous mode) you'd block for 
      }
    }
  </script>
<!--- ... --->

and the JS file:

// somefile.js
// some JS code goes here
// ...snip...
notify_file_is_loaded('somefile.js');

Get the JS synchronously instead. Just append a script tag to html > head with src="<script-location>" and the browser will do this download synchronously.

going on a tanget here: It is poor user-experience to block until something has downloaded. If you write your code using principles of graceful degradation, your page should only activate functionality that is available. Would you let another web-developer subject you to this. No I wouldn't - I would close that tab and move on :)

Are you deferring the loading of the JavaScript file via JavaScript? If so you should be able to use the onload event handler to execute your code after the JavaScript file has been loaded:

<script>
    var js = document.createElement('script');
    js.onload = function() {
        // your code goes in here
    }
    js.src = 'foo.js';
    document.body.appendChild(js);

</script>

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