0

I've read here that the below method can add a performance penalty

var formsCount = 0;  

new MutationObserver(function(mutations, observer) {
let formLength = document.getElementsByTagName('form').length;
        if (formsCount != formLength) {
            formsCount = formLength;

            // Do something here
            console.log('we observed')
        }  
}).observe(document.getElementsByTagName('body')[0], {subtree:true, childList: true});

So is the above or the below likely to be better for performance?

setInterval(function () {
            var formLength = document.getElementsByTagName('form').length;
            if (formsCount != formLength) {
                formsCount = formLength;

                // Do something here
                console.log('we observed')
            }
        }, 1000);

PS. I know getElementsByTagName('form') updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again, so possibly moving up the scope could gain some performance but I've put the naive version for readability

Edit: (for the MutationObserver, I was initially attempting to select just the forms, but actually we need to observe the parent... and that needs to be body as we don't know where the form will be appended)

  • I'm not familiar with `MutationObserver` but if it does what is says on the [box](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), it's obviously far more efficient, since it only fires when an actual mutation took place, in contrast with `setInterval` that checks for changes even if there are none. – nicholaswmin Mar 07 '18 at 10:52
  • @NicholasKyriakides If you asked me, I can either hit you continually with this feather or once with a hammer, I'd ask - how big's the hammer...? – Wayne Theisinger Mar 07 '18 at 11:36
  • 1
    Touche; I'll slowly back off now, although I still believe the `MutationObserver` is far more performant; I'll leave this for someone else to answer. – nicholaswmin Mar 07 '18 at 11:37

0 Answers0