I am working on a small JavaScript template engine, and I have two possible approaches for dealing with updates to the DOM when the model changes:
Check if the DOM update is really needed before doing it. This has the benefit of not risking unnecessary updates, but I am wasting space on keeping track of old values.
if (oldValue !== newValue) { element.textContent = newValue; }Just do it. This is obviously simpler, but I am afraid that I will be triggering repaints and reflows for no reason.
element.textContent = newValue;
Note that I am also manipulating the DOM by calling setAttribute, addClass and removeClass, plus setting style[prop] = value.
So, my question is: Are modern browsers smart enough to notice that nothing actually changed, and therefore not run reflow or repaint, if you touch the DOM without actually changing anything?
Using the
MutationObserverapi you can detectDOMchanges.Here is an example you can use to see if a browser triggers the
Dom Changedevent, based on what you want.You have here both a
text('...')by jquery and anel.textContent(that doesn't use jquery).setAttribute()and jQuerytext()triggered theDom Changeevent.Dom Changeevent.Dom Changeevent.