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)