4

I use dynamic script tags to request javascript from external domains. 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.

Thanks!

rawrrrrrrrr
  • 3,387
  • 7
  • 24
  • 32
  • 1
    I'd assume they mean a script tag that is itself written into the page by an existing script (so as to load a new script on-the-fly). – Amber Aug 08 '09 at 00:44
  • Not sure why this was modded down, I didn't see any reason for it to be. +1 to compensate. – Josh Aug 08 '09 at 14:46

1 Answers1

0

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

   <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

Community
  • 1
  • 1
Andrea Fiore
  • 1,568
  • 2
  • 12
  • 17
  • 1
    This doesn't appear to work. I created a script that sleeps for 10 seconds, and then returns and inserted it as a script src, and the request is not canceled. – Josh the Goods Aug 30 '10 at 19:24