views:

65

answers:

2

Is it somehow possible to stop a script tag from loading after is has been added to the head of a HTML document?

I would like to have something like this:

var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
document.getElementsByTagName('head')[0].appendChild(script_tag);

// something like this!!!
script_tag.abort();
+1  A: 

I very much doubt this is possible. As soon as the script tag is added to the head it will be downloaded and parsed and even removing the node won't stop it.

Andy E
A: 

No you can't do this this way. But you can if you load it via XMLHTTPRequest (AJAX). This way you can abort connection if it takes too long.
For example you can use timeout option if you use jQuery:

$.ajax({ url: "a.js", dataType: "script", timeout: 1000});

This way if script doesn't load within 1 sec (1000ms) request will be aborted. Also you can use {async:false} to prevent code execution while script is loading (if you need to).

Check http://api.jquery.com/jQuery.ajax/ for more options.

NilColor
Thanks for the answer but that does not always work due to cross domain restrictions.
Martin Wittemann
What about `jsonp`? This way you can do crossdomain. But be sure you trust that domain.
NilColor
JSONP is just dynamic `<script>` tag injection, so the same problem with not being able to abort an existing request is there.
Roatin Marth