The day has finally come,… to spread awareness regarding a concept called Mutation Observer. Yes, you should know about this. Simple but still a game changer when it comes to controlling how your webpage interacts with a user.
I’m saying it with no regrets, let’s just
What if there is a way you can manipulate DOM more easily and in better optimized way. Yes there is
MutationObserver is a built-in object that observes a DOM element and fires a callback when it detects a change.
So what is means is that it allows you to detect when elements in a web page are inserted, changed,or removed. It is still relatively new, but it is supported by every modern browser.
First, we create an observer with a callback-function:
let observer = new MutationObserver(callback);
And then attach it to a DOM node:
Then after any changes, the callback is executed: changes are passed in the first argument as a list of MutationRecord objects, and the observer itself as the second argument.
It’s pretty simple once you get a hang of it.
For a deeper dive into web mutations, visit here.
So what is the need for it? Is there any real-life scenario to use this over anything else?
Client-side Image Optimization
Believe it or not, it’s actually possible to swap the src’s of img tags before the browser begins to load them. We can use that to optimize our images without changing the HTML source of our page.
Initializing When An Element Becomes Available on the Page
It’s a common pattern to wait for jQuery.ready or DOMContentLoaded to initialize code which depends on elements on the page. Those events don’t fire until the entire DOM has loaded however meaning the page will start to be rendered before you have a chance to change or add to its content.
Managing ContentEditable Regions
If you are truly building an editor, it’s common to want some control over what the user can enter. You can use MutationObservers to prevent certain modifications or take action when they occur.
As our marathon to make our development load fast on the client’s machine is not coming to an end. These simple hacks of loading what’s necessary, optimizing assets for a device among other things make a huge difference for someone picking your product over others.