问题
I failed to observe document.write
on document.body
. Here is code:
<script>
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
eventListenerSupported = window.addEventListener;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback();
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( eventListenerSupported ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
window.onload = function() {
//console.log("dom ready");
// Observe a specific DOM element:
observeDOM( document.body ,function(){
console.log('dom changed');
});
}
function reload() {
document.write("<input type=\"submit\" onclick=\"reload();\" value=\"Reload\" />");
//var text = document.createTextNode("abc");
//document.body.appendChild(text);
}
</script>
<body>
<input type="submit" onclick="reload();" value="Reload" />
</body>
When I click Reload
button, nothing logged. But if I change code in window.onload
to:
observeDOM( document ,function(){ // change first parameter to *document*
console.log('dom changed');
});
And then click Reload
, console outputs dom changed
. Could anyone tell why? I'm using Chrome v50.
回答1:
I find the reason today. It seems that document.write()
covers old document.body
with a new one. Since MutationObserver was attached to old document.body
, it can't observe DOM change on new body
.
Here is how I tested it:
来源:https://stackoverflow.com/questions/37110926/why-cant-observe-document-write-on-document-body-using-mutationobserver-api