By Mihnea Dobrescu-Balaur on July 15, 2014
Here at Hootsuite, we love to open source components that we develop for ourselves and might be useful to others. We feel that this is a great way to help to give back and contribute to the Open Source ecosystem.
While performing some refactoring on our fronted code, we managed to isolate a component that we use for observing DOM changes, as well as reacting to those changes. The reason we developed this code was that alternatives such as mutation-summary did not do all we wanted, and even now, they don’t offer fallback support, which we need since we support older versions of IE as well.
DOMObserver exposes an API that lets you set handlers for when:
- a node is added to the DOM
- a node is removed from the DOM
- a node’s attributes are changed
The handlers receive the mutation target as a parameter, so you know which node changed. Furthermore, if you want to do more advanced things, the handlers also receive the mutation (event) object, so you can tell exactly what has changed.
As far as performance goes – you can set the handler on a specific DOM node, so there is no need to listen on the whole document. Also, for attribute changes you can filter the attributes you care about (so for example you only get notified when data-loaded is changed, but not for src changes). When you are no longer interested in the DOM changes (say your app reaches a constant, immutable state), you can simply shutdown the observer.
uberVU is part of the Hootsuite team. Read more about it here