javascript - Why can't observe document.write on document.body using MutationObserver API? -
i failed observe document.write
on document.body
. here code:
<script> var observedom = (function(){ var mutationobserver = window.mutationobserver || window.webkitmutationobserver, eventlistenersupported = window.addeventlistener; return function(obj, callback){ if( mutationobserver ){ // define new observer var obs = new mutationobserver(function(mutations, observer){ if( mutations[0].addednodes.length || mutations[0].removednodes.length ) callback(); }); // have observer observe foo 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 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 click reload
button, nothing logged. if change code in window.onload
to:
observedom( document ,function(){ // change first parameter *document* console.log('dom changed'); });
and click reload
, console outputs dom changed
. tell why? i'm using chrome v50.
i find reason today. seems document.write()
covers old document.body
new one. since mutationobserver attached old document.body
, can't observe dom change on new body
.
here how tested it:
Comments
Post a Comment