Sunday, April 7, 2013

JavaScript: The less known parts. DOM Mutations.

'JavaScript: The less known parts' chapters:
1. Bitwise Operators
2. Storage
3. Dom Mutations

At the beginning of last May, so not even a year ago, there was quite a buzz around a blogpost by David Walsh about detecting DOM Node insertions with JavaScript and CSS Animations. In the article, David explained that even if Mutation Events are deprecated, we are not powerless in detecting DOM modifications in our JavaScript code - using simple hack (and since we are web developers, we love hacks and we use tons of them every day), we can attach very short (0.001s in the given example) animation to every element that will be added to to DOM Tree, and then listen to the animationstart event. The animation will be to short to notice it, so the event will fire almost immediately after DOM modification. Full post is still online, you can find it in here - Detect DOM Node Insertions with JavaScript and CSS Animations. Great, but is it the only way to detect node changes in JavaScript? Fortunately - it's not. Say hello to the MutationObserver.

About three days after David's article, Jeff Griffiths presented MutationObserver on MozHacks in an article called DOM MutationObserver – reacting to DOM changes without killing browser performance. In just a few words, MutationObserver provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification. It's way simpler and more efficient to use native browser's API than hundreds of hacks - we are creating more dynamic webapps all the time, so it seems natural that we would welcome the ability to listen for changes in the DOM and react to them.

Below, I've reimplemented the demo from David's blogpost from CSS Animations to MutationObserver. You can find the original example here: Detect code insertion.

Unfortunately, MutationObserver is still a fresh feature, and it isn't supported everywhere - we can use it in only in Chrome (Desktop) & Firefox (Desktop & Android) so far:

MutationObserver resources

DOM Mutation Observers & The Mutation Summary Library
Mutation Summary
MutationObserver on MDN
MutationObserver DOM4 Spec
Detect DOM changes with Mutation Observers - HTML5Rocks
DOM MutationObserver – reacting to DOM changes without killing browser performance.

Do you find this kind of API useful? Do you know any other hacks related to DOM manipulation listeners? Comment here or catch me on Twitter (@michalbe).