Search code examples
javascriptdommutation-observers

Usage of MutationObserver in a page that is not dynamically modified


This seems like an obvious question but I can't find any definitive answer in any documentation.

I want to make sure that a function is ran when the page is loaded at first and when the page is modified by adding or removing a node.

Is a MutationObserver supposed to trigger on page load, at least once, when the DOM is parsed, even if there is no JS that adds or removes nodes?

My testing seems to indicate that it is. The Observer always gets at least one record, that includes the whole body of the document, when I get it to observe document.body with childList on true. However, I'd like to have a definitive answer, ideally from documentation (which I can't find), since perhaps this is browser dependant in some way.

This is the simple code I'm using to test:

<!DOCTYPE html> 
<head>  
  <title>Observer test</title>
</head>
<body>              
<script type='text/javascript'>
  var config = { childList: true, subtree: true };

  function mutationCallback (mutationsList, observer) {
    console.log('Triggered');
      for(let mutation of mutationsList) {
       console.log(mutation.type);
       console.log(mutation.target);
         for (let node of mutation.addedNodes) {
           console.log(node)
         }
      }
  }
  observer = new MutationObserver(mutationCallback);
  observer.observe(document.body, config);
</script>
</body>
</html>

Solution

  • Is a MutationObserver supposed to trigger on page load, at least once, when the DOM is parsed, even if there is no JS that adds or removes nodes?

    No, page load event is not related.

    The observer is triggered only by DOM mutations (either in JS or in HTML parser) and you happen to have one here as well. To see it easily add a console.log for the entire list: console.log(mutationsList)

    You will see that the only mutation is the addition of a text node containing spaces/newlines between the tags </script> and </body>.

    enter image description here