Sep*_*eed 5 javascript mutation-observers
该DOMNodeInserted事件已被弃用,所有突变事件均已替换为突变观察者。
但是,在突变观察者中,只有用于观察节点属性、内容和子节点突变的配置选项。没有关于它在 DOM 树中的位置的变化。
我能想到的一个“解决方案”是观察从 document.body 开始的所有内容,搜索正在添加的目标节点的一个突变,但这是一种非常糟糕的做任何事情的方式。
那么用 Mutation Observers 替换已弃用的 DOMNodeInserted 的预期方法是什么?
编辑:发现可能的重复 检测具有特定 ID 的元素何时插入 DOM 中的最有效方法是什么
再说一遍:搜索栏与标签一起使用比与问题一起使用效果更好。解释这一点可以减少重复并节省用户时间
下面是一些代码,您可以在其中看到所有可用的突变观察者配置选项都不会响应添加到页面的元素:
var addMe = document.createElement("div");
var config = {
attributes: true,
childList: true,
characterData: true
}
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
});
observer.observe(addMe, config);
function appendAddMe() {
document.body.appendChild(addMe);
}Run Code Online (Sandbox Code Playgroud)
div {
height: 50px;
width: 50px;
background: #969;
}Run Code Online (Sandbox Code Playgroud)
<button onclick="appendAddMe()">Append addMe</button>Run Code Online (Sandbox Code Playgroud)
我真的不认为这是问题的答案,但无论如何我想分享它,因为它总比没有好。
这个问题有一些很好的答案:What is the most effective way of detector when a element with a certain ID is inserting in the DOM
特别是,这个答案: https: //stackoverflow.com/a/25107064/4808079 来自schettino72
iframe 元素触发 load/unoad 事件。您可以在要观看的元素中插入一个哑iframe...并自己在原始元素中触发“加载”事件。
function watch($ele){
var $iframe = document.createElement('iframe');
$iframe.style.display = 'none';
$ele.appendChild($iframe);
$iframe.addEventListener('load', function(){
var event = new CustomEvent('load');
$ele.dispatchEvent(event);
});
}
Run Code Online (Sandbox Code Playgroud)
我仍然想保持这个问题的开放性,因为这是一个黑客而不是一个真正的答案。DOMNodeInserted 可能没有被弃用,所以每个人都可以这样做。