22 Haziran 2019

Mutation observer

MutationObserver is a built-in object that observes a DOM element and fires a callback in case of changes.

We’ll first see syntax, and then explore a real-world use case.

Syntax

MutationObserver is easy to use.

First, we create an observer with a callback-function:

let observer = new MutationObserver(callback);

And then attach it to a DOM node:

observer.observe(node, config);

config is an object with boolean options “what kind of changes to react on”:

  • childList – changes in the direct children of node,
  • subtree – in all descendants of node,
  • attributes – attributes of node,
  • attributeOldValue – record the old value of attribute (infers attributes),
  • characterData – whether to observe node.data (text content),
  • characterDataOldValue – record the old value of node.data (infers characterData),
  • attributeFilter – an array of attribute names, to observe only selected ones.

Then after any changes, the callback is executed, with a list of MutationRecord objects as the first argument, and the observer itself as the second argument.

MutationRecord objects have properties:

  • type – mutation type, one of
    • "attributes": attribute modified
    • "characterData": data modified, used for text nodes,
    • "childList": child elements added/removed,
  • target – where the change occurred: an element for “attributes”, or text node for “characterData”, or an element for a “childList” mutation,
  • addedNodes/removedNodes – nodes that were added/removed,
  • previousSibling/nextSibling – the previous and next sibling to added/removed nodes,
  • attributeName/attributeNamespace – the name/namespace (for XML) of the changed attribute,
  • oldValue – the previous value, only for attribute or text changes.

For example, here’s a <div> with contentEditable attribute. That attribute allows us to focus on it and edit.

<div contentEditable id="elem">Click and <b>edit</b>, please</div>

<script>
let observer = new MutationObserver(mutationRecords => {
  console.log(mutationRecords); // console.log(the changes)
});
observer.observe(elem, {
  // observe everything except attributes
  childList: true,
  subtree: true,
  characterDataOldValue: true
});
</script>

If we change the text inside <b>me</b>, we’ll get a single mutation:

mutationRecords = [{
  type: "characterData",
  oldValue: "me",
  target: <text node>,
  // other properties empty
}];

If we select and remove the <b>me</b> altogether, we’ll get multiple mutations:

mutationRecords = [{
  type: "childList",
  target: <div#elem>,
  removedNodes: [<b>],
  nextSibling: <text node>,
  previousSibling: <text node>
  // other properties empty
}, {
  type: "characterData"
  target: <text node>
  // ...details depend on how the browser handles the change
  // it may coalesce two adjacent text nodes "Edit " and ", please" into one node
  // or it can just delete the extra space after "Edit".
  // may be one mutation or a few
}];

Observer use case

When MutationObserver is needed? Is there a scenario when such thing can be useful?

We can track something like contentEditable and implement “undo/redo” functionality (record mutations and rollback/redo them on demand). There are also cases when MutationObserver is good from architectural standpoint.

Let’s say we’re making a website about programming. Naturally, articles and other materials may contain source code snippets.

An HTML markup of a code snippet looks like this:

...
<pre class="language-javascript"><code>
  // here's the code
  let hello = "world";
</code></pre>
...

Also we’ll use a JavaScript highlighting library on our site, e.g. Prism.js. A call to Prism.highlightElem(pre) examines the contents of such pre elements and adds into them special tags and styles for colored syntax highlighting, similar to what you see in examples here, at this page.

When to run that method? We can do it on DOMContentLoaded event, or at the bottom of the page. At that moment we have DOM ready, can search for elements pre[class*="language"] and call Prism.highlightElem on them:

// highlight all code snippets on the page
document.querySelectorAll('pre[class*="language"]').forEach(Prism.highlightElem);

Now the <pre> snippet looks like this (without line numbers by default):

// here's the code
let hello = "world";

Everything’s simple so far, right? There are <pre> code snippets in HTML, we highlight them.

Now let’s go on. Let’s say we’re going to dynamically fetch materials from a server. We’ll study methods for that later in the tutorial. For now it only matters that we fetch an HTML article from a webserver and display it on demand:

let article = /* fetch new content from server */
articleElem.innerHTML = article;

The new article HTML may contain code snippets. We need to call Prism.highlightElem on them, otherwise they won’t get highlighted.

Where and when to call