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.getElementsByT开发者_StackOverflow社区agName('head')[0].appendChild(script_tag);
// something like this!!!
script_tag.abort();
It's not possible in any cross-browser manner. 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.
That being said, Firefox has document.onbeforescriptexecute
, which is cancellable (where the default action would be to execute the target script). This event was originally on a standards track but was recently removed from the HTML spec due to a lack of valid use cases.
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.
Microsoft Edge and Internet Explorer do allow you to cancel scripts loading:
remove the script from the page e.g.
<script id=blah src=...></script>
andblah.parentNode.removeChild(blah);
then do a garbage collection
window.CollectGarbage && CollectGarbage();
(not always necessary since large page will cause a GC to happen anyway)don't try testing using the debugger (it interferes, e.g. GC)
you need a
<script async
(or defer?) property, otherwise later scripts won't execute on the page (note your scripts must correctly handle out-of-order script loading due to theasync
property).IE/Edge only act as if the script loaded, but they don't actually close the connection (not sure what it does if the script eventually does load).
this technique stops the throbber, makes the pageload event fire (very important for jQuery), and resize events fire (otherwise they don't while page is "loading").
the technique doesn't work for Chrome or Firefox
an XMLHttpRequest (CORS if necessary) is likely a far better implementation since you can control the timeout and abort()
I only tested Internet Explorer 11 and Edge 13
精彩评论