WinJS 2.0 / IE 11 : the new and shiny MutationObserver object

, , 1 Comment

Let me introduce you a new feature of Internet Explorer 11 which is available in your Windows 8.1 apps too : the MutationObserver. This object lets you observe the changes on any HTML element of your DOM.

You may already know these monitoring events available before and which are now no more supported :

  • DOMNodeInserted
  • DOMNodeRemoved
  • DOMSubtreeModified
  • DOMAttrModified
  • DOMCharacterDataModified

They have been replaced by the MutationObserver in IE 11 because they have several drawbacks:

  • They are standard JS events, so they bubble the whole DOM : bad for performance.
  • They may spam you because each change raise an event without batching : bad for performance.
  • They are synchronous and block your execution : bad for performance.
  • Did I tell you that there may be performance issues?

The MutationObserver fix these issues and is really easy to use :

  1. Create a mutation observer by giving a callback function as a parameter.
  2. Observe an element and specify “what to observe”
  3. Do something in the callback

Creating a mutation observer is easy as instantiating an object. The callback function takes 2 parameters : an object describing the change and the second one will be the MutationObserver.
[js]function mutationObserverCallBack(changes, mutationObserver) {/*…*/ }

//Creation of the observer
var observer = new MutationObserver(mutationObserverCallBack);[/js]

Then you can observe any html element by calling the observe function on the observer. This function takes as a second parameter a json object with the “monitoring” options. For example, you can monitor only the addition/removal of element on any of its children and any change of “class” :
var observer = new MutationObserver(mutationObserverCallBack);
observer.observe(element, {
attributes: true,
attributeFilter: ["class"],
childList: true,
subtree: true,
There is a lot of possible configuration and you can find a full list on this MSDN page.

In the callback, you can explore the changes which is a list of the modifications. Each one has a type field and some properties (added nodes, old value, etc.) which let you know which change has been performed.
[js]function mutationObserverCallBack(changes, mutationObserver) {

changes.forEach(function (mutationRecord) {

console.log("Type of mutation: " + mutationRecord.type);

if ("attributes" === mutationRecord.type) {
console.log("Old attribute value: " + mutationRecord.oldValue);


Additionnal links

This is a just a quick blog post of this good new API. You can find more information on these pages :


One Response

Comments are closed.