简体   繁体   English

Javascript:“取消”动态脚本标记?

[英]Javascript: “Cancelling” a dynamic script tag?

I use dynamic script tags to request javascript from external domains. 我使用动态脚本标记从外部域请求javascript。 Sometimes the request takes too long; 有时请求时间太长; is it possible to stop the request or timeout if the requests takes too long? 如果请求时间过长,是否可以停止请求或超时?

I do not want to use xmlhttprequest because I'd like to avoid having to use a server side proxy. 我不想使用xmlhttprequest,因为我想避免使用服务器端代理。

Thanks! 谢谢!

Having said that there are different ways of adding a script dynamically, a way of doing this is by appending a <script> node to the document's body when the DOM is ready, and then removing it if it takes to long to load.. 虽然说有不同的动态添加脚本的方法,但是这样做的方法是在DOM准备就绪时将<script>节点附加到文档的主体,然后在需要很长时间加载时删除它。

   <html>
    <head>
    <title>bla</title>
    <script type="text/javascript">
      function init(){
         var max_time = 2000 //in milliseconds
         g_script_url = "http://yoursite.net/script.js";
         var script = document.createElement("script"); 
         script.setAttribute("src",script_url);
         script.setAttribute("type","text/javascript");   
         document.body.appendChild(script);   

         g_timeout=setTimeout(function(){ 
           var scripts = document.getElementsByTagName("script");
           for (var i=0; i < scripts.length; i++ ){
           if (scripts[i].src == script_url){
              document.body.removeChild(scripts[i]);
            }
           }   
          },max_time);
        }

     window.addEventListener("DOMContentLoaded", init, false);
    </script>
  </head>
   <body>bla bla [...]</body>
  </html>

Then you can add an instruction to clear the timeout at the end of the dynamically loaded script: 然后,您可以添加一条指令以清除动态加载脚本末尾的超时:

/* end of http://yoursite.net/script.js's code */
clearTimout(g_timeout);

NOTE: 注意:

document.addEventListener does not work in IE, if you want a cross platform solution use Jquery's method $(document).ready or have a look at Document ready equivalent without JQuery document.addEventListener在IE中不起作用,如果你想要一个跨平台的解决方案使用Jquery的方法$(document).ready或者看看没有JQuery的Document ready等价物

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

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