DOM mutation events replacement

Franck Freiburger picture Franck Freiburger · Mar 24, 2011 · Viewed 19k times · Source

Since DOM mutation is marked as deprecated by the w3c (see http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents), is there an (fast) alternative way to detect attribute modification in the DOM ?

Answer

ama2 picture ama2 · Jun 19, 2012

The reason that mutation events was deprecated was because of huge performance issues.

The replacement is Mutation Observers, look at http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers and https://developer.mozilla.org/en/DOM/DOM_Mutation_Observers

Information about mutations is delivered to observers as an ordered sequence of MutationRecords, representing an observed sequence of changes that have occurred

Sample usage:

    var observer = new MutationObserver(function(mutationRecords) {
    // Handle mutations
     });

    observer.observe(myNode,
     {  // options:
     subtree: true,  // observe the subtree rooted at myNode
     childList: true,  // include information childNode insertion/removals
     attribute: true  // include information about changes to attributes within the subtree
    });

This is supported in Chrome 18 and Firefox and Webkit nightly builds. Firefox 14 will also be supporting this feature.