Javascript: "Canceling" a dynamic script tag?

I am using dynamic script tags to request javascript from external domains. Sometimes a request takes too much time; is it possible to stop a request or timeout if requests take too long?

I do not want to use xmlhttprequest because I would like to avoid using a server-side proxy.

Thanks!

+4
source share
1 answer

Having said that there are various ways to add a script dynamically, the way to do this is by adding a <script> node to the body of the document when the DOM is ready, and then delete it if it takes a long time to load.

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

You can then add an instruction to reset the timeout at the end of the dynamically loaded script:

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

Note:

document.addEventListener does not work in IE if you want a cross-platform solution to use the Jquery $ (document) .ready method or look at the equivalent of a document without jQuery

0
source

All Articles