警告:这里我假设<div>
插入结果的位置是已知的。
一个可能的解决方案是使用一个MutationObserver
(和DOMNodeInserted
事件,以支持 IE 9 和 10)来观察所述<div>
内容的变化,并在任何插入的<script>
标签上执行代码。
基于您的 jsFiddle 构建的示例:
watchNodeForScripts(document.getElementById("xxx"));
function watchNodeForScripts(scriptRecipient) {
if ('MutationObserver' in window) {
// Prefer MutationObserver: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
watchUsingMutationObserver();
} else {
// Fallback to Mutation Events: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Events/Mutation_events
watchUsingDeprecatedMutationEvents();
}
function watchUsingMutationObserver() {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var i, addedNodes = mutation.addedNodes;
for (i = 0; i < addedNodes.length; i++) {
handleAddedNode(addedNodes[i]);
}
});
});
observer.observe(scriptRecipient, {
childList: true
});
}
function watchUsingDeprecatedMutationEvents() {
scriptRecipient.addEventListener("DOMNodeInserted", function (event) {
handleAddedNode(event.target);
});
}
function handleAddedNode(node) {
// Don't try to execute non-script elements
if (!(node instanceof HTMLScriptElement)) return;
// Don't try to execute linked scripts
if (node.src !== "") return;
// Use 'new Function' instead of eval to avoid
// the creation of a (undesired) closure
fn = new Function(node.textContent);
fn.call(window);
}
}
更新小提琴:http: //jsfiddle.net/7hWRR/13/
编辑:更改innerText
为更交叉兼容的textContent
.
Edit2:不要执行不在<script>
元素内的代码。
Edit3:不要执行带有src
属性的脚本,并添加突变事件回退