问题
The DOMNodeInserted event has been deprecated and all Mutation Events have been replaced with mutation observers.
But, within mutation observers there are only config options for watching mutations to the nodes attributes, content, and children. Nothing about a mutation to it's placement in the DOM tree.
There is one "solution" I can think of which is to observe everything from document.body down searching for the one mutation which is my target node being added, but that's a pretty awful way of doing anything.
So what is the expected way to replace the deprecated DOMNodeInserted with Mutation Observers?
EDIT: found possible duplicate What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM
Once Again, SO: The searchbar works better with Tags than Questions. Explaining this could reduce duplicates and save users time
Below is some code where you can see that none of the available mutation observer config options respond to the element being added to the page:
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);
}
div {
height: 50px;
width: 50px;
background: #969;
}
<button onclick="appendAddMe()">Append addMe</button>
回答1:
I don't really consider this to be the answer to the question, but I'd like to share it anyways because it's better than nothing.
This question has some good answers: What is the most efficient way of detecting when an element with a particular ID is inserted in the DOM
In particular, this answer: https://stackoverflow.com/a/25107064/4808079 from schettino72
iframe elements trigger load/unoad events. You can insert a dumb iframe in the element you want to watch... And trigger a 'load' event in the original element yourself.
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);
});
}
I would still like to keep this question open as this is a hack and not a true answer. DOMNodeInserted was probably not deprecated so everyone could do it this way instead.
来源:https://stackoverflow.com/questions/40364156/what-is-the-new-equivalent-of-domnodeinserted