Detecting new DOM additions using Sentinel JS

Image for post
Image for post

Today I stumbled upon this simple library called Sentinel.JS that allows us to detect new DOM elements added to the DOM tree.

This is a task that can be accomplished using the Mutation Observer interface, but this library makes it pretty simple and that’s what I like about it. This is what the creator of the library says about its implementation:

SentinelJS uses dynamically-defined CSS animation rules (@keyframes) to hook into browser animationstart events when a new node matching a given CSS selector is added to the DOM. In general this should be more performant than using a Mutation Observer to watch the entire document tree for changes and iterating through all new child nodes recursively.

The “more performant” part makes sense in this case, but I’ll leave that verification for another post.

Now, the library is pretty simple to use, once you have it included in your page, you can bind to DOM addition events by using the on method, like this:

As you can see, you only need a CSS selector (of the element you want to detect when gets added to the DOM) and a callback function that will get executed when that happens. Yes, as simple as that. So a real example could be:

In the example above, we’re listening for additions of an “li” tag and when that happens, we call the addNotification function.

If we want to remove the listener, we can do it with:

Here’s an example in Codepen

The library has other cool features like listening to multiple elements, triggering a watch function using custom CSS, etc. You can see more in the official documentation.

As always, let me know your thoughts.

Software Engineer - VP Architect @Digitas

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store