且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有可能停止动态插入的脚本标记?

更新时间:2023-12-05 08:08:52

无法以任何跨浏览器的方式进行。只要脚本标签被添加到头部,它就会被下载并解析,甚至删除节点也不会阻止它。



就是说,Firefox有 document.onbeforescriptexecute ,这是可以取消的(默认操作是执行目标脚本)。这个事件最初是在标准轨道上,但由于缺少有效的用例,最近从HTML规范中删除。


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();

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.