简体   繁体   English

如果JS下载未完成,如何阻止

[英]How to block if JS download is not completed

I am downloading the JS file asynchronously by appending the JS file to HTML head. 我通过将JS文件附加到HTML头来异步下载JS文件。 Now in html body, before using the JS file, I want to check if JS file has downloaded and is present in the cache. 现在在html正文中,在使用JS文件之前,我想检查JS文件是否已下载并且是否存在于缓存中。 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. 如果缓存中不存在JS文件(例如,在互联网连接缓慢的情况下),我想阻止它下载。 In other words, if JS download is not complete, i want to simulate the behavior as in the case of blocking JS download. 换句话说,如果JS下载未完成,我想模拟行为,就像阻止JS下载一样。

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. 如果您可以控制HTMl文件和JS文件,请执行以下操作:在已加载的代码中的某个位置定义“回调”函数,然后从JS文件的末尾调用它。 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: 和JS文件:

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

Get the JS synchronously instead. 同步获取JS。 Just append a script tag to html > head with src="<script-location>" and the browser will do this download synchronously. 只需将脚本标记附加到html > head并使用src="<script-location>" ,浏览器将同步进行此下载。

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. 您是否可以让另一个Web开发人员对此进行管理? No I wouldn't - I would close that tab and move on :) 不,我不会-我将关闭该标签并继续:)

Are you deferring the loading of the JavaScript file via JavaScript? 您是否正在推迟通过JavaScript加载JavaScript文件? If so you should be able to use the onload event handler to execute your code after the JavaScript file has been loaded: 如果是这样,您应该能够在加载JavaScript文件之后使用onload事件处理程序执行代码:

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

</script>

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

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