MutationObserver in rules — a rule that keeps up with the page
Your rule runs after the page loads — but modern pages do not end at load. A list pulls in more entries, an SPA swaps whole views, content shows up seconds later. A MutationObserver makes the rule react to what happens after start.
The problem: code runs once
The JavaScript of a JustZix rule runs once, when the page loads. If you hide .promo and the page adds more .promo on scroll, your code never saw them — they did not exist yet. You need something that reacts to a change in the DOM.
MutationObserver in three lines
function apply() {
document.querySelectorAll('.promo').forEach(el => el.remove());
}
apply();
new MutationObserver(apply)
.observe(document.body, { childList: true, subtree: true });
The pattern is always the same: an apply function does the work, you call it once right away, then hand it to the MutationObserver to call on every change.
What the observe options mean
childList: true— react when child elements are added or removed.subtree: true— observe not just direct children but the whole subtree. Without it, changes deep in the DOM are missed.attributes: true— optional: react to attribute changes (classes,style) too.
Pitfall one — the feedback loop
If apply changes the DOM itself (and it usually does), that change fires the observer, which calls apply again. For hiding that is usually harmless — the second pass has nothing left to do. But if apply adds something, mark the done elements:
function apply() {
document.querySelectorAll('.card:not([data-jz])').forEach(el => {
el.dataset.jz = '1';
el.prepend(makeBadge());
});
}
The :not([data-jz]) selector makes you handle each element exactly once — the loop does not spin up.
Pitfall two — the cost
On very dynamic pages the observer fires hundreds of times. Keep apply cheap: a fast querySelector, a "done" marker, no heavy computation. If it has to be heavy — wrap it in a debounce (defer execution by 100 ms and reset the timer on each new change).
See also
- Rules resilient to DOM changes — a wider set of techniques
- Auto-expand — MutationObserver in practice
- Examples — ready-made rules to study
Install JustZix — and write rules that keep up with the page.
Rate this post
No ratings yet — be the first.