如何在执行脚本元素之前将其删除?

Alo*_*kin 9 jquery

如何在执行脚本元素之前将其删除?

我想过使用DOMNodeInserted事件,但显然它没有捕获脚本元素.我也尝试过使用jQuery livequery插件:

$("script").livequery(function () { 
    $(this).remove();
});
Run Code Online (Sandbox Code Playgroud)

它确实删除了脚本元素,但是在执行之后.

我正在寻找一个跨浏览器的解决方案,但我甚至不确定这是否可行.我读到了Mutation Observers,它似乎足够接近,但我不确定它是否可以解决我的问题.

如果有一种方法可以在执行脚本内容之前修改脚本内容而不删除并重新创建脚本内容,那就更好了.

Esa*_*ija 11

删除脚本元素不会执行任何操作.如果你能以某种方式访问​​一个脚本元素,它很久以前就被执行了,删除它将没有任何效果.

所以我们需要解决它.如果您的脚本元素位于页面顶部,如下所示:

<head>
    <script src="yourscript.js"></script>
Run Code Online (Sandbox Code Playgroud)

您可以对同一页面发出同步ajax请求,因此您可以将其内容解析为新文档,修改所有脚本标记,然后用修改后的文档替换当前文档.

var xhr = new XMLHttpRequest,
    content,
    doc,
    scripts;

xhr.open( "GET", document.URL, false );
xhr.send(null);
content = xhr.responseText;

doc = document.implementation.createHTMLDocument(""+(document.title || ""));

doc.open();
doc.write(content);
doc.close();


scripts = doc.getElementsByTagName("script");
//Modify scripts as you please
[].forEach.call( scripts, function( script ) {
    script.removeAttribute("src");
    script.innerHTML = 'alert("hello world");';
});

//Doing this will activate all the modified scripts and the "old page" will be gone as the document is replaced
document.replaceChild( document.importNode(doc.documentElement, true), document.documentElement);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不能在jsfiddle或jsbin中设置.但您应该能够将此代码完全复制粘贴到Google Chrome浏览器的此页面控制台中.您应该看到警报,当您检查实时dom时,每个脚本都被修改.

不同之处在于我们在页面上执行脚本后运行此脚本,因此旧脚本仍应对页面起作用.这就是为什么要使这个工作,你需要成为页面上第一个执行此操作的脚本.

经测试可在谷歌浏览器中使用.doc.write由于某些原因,Firefox完全忽略了这个调用.