Introducing: Bad-DOM – the smallest* component renderer

*seriously, it’s 800 bytes minified + gzipped – Get it on Github


I took some notes while I worked on this project. Here they are.


Building a dom diffing algorithm


– can it be recursive?


– function w/3 params: target (thing to change), source (html string), root (working record of changes)


– 6 types of changes possible: nodeName, style, attribute, class, id, or innerContent


– get rid of root parameter for now, too confusing to think about


– create template, inject string, get new unrendered html inside template w/first 4 lines of vDiff function


– refactor to object with methods


– make super modular with recursive iterate method and individual functions to check 5 possible changes, iterate function should know if is top level node






all of these must know if elem is node or text content


– iterate recursive function should return iterate on childnodes or next sibling. use nextSibling instead of nextElementSibling so that whitespace is accounted for

– what to do if source contains additional node instead of alteration?

– text content switch was hardest, in some cases, parentElement doesn’t exist on #textnode, solved by checking childNodes array to see if textNode exists (L28)

– can remove checkID/checkClass functions because check attributes takes care of it


– now comes the interesting part – we need to check for new nodes in the source, and add them to the target

– need to replace line breaks and indents, which aren’t in target, but are in source template string / babel

– for some reason, a span is disappearing

 – this was happening because replace child was removing the new element from source and moving it into target – solved with node.cloneNode(true)

– iterating over element.children is much quicker / easier / less lines – refactoring – did in 10 lines what originally took 22


– we need to iterate over whichever element (source vs target) has the most children, in the likely case that the 2 objects to diff have a different # of nodes and we need to remove / add some

– need to adjust code to address for html comments, which have their own node type, in doing so also addressing the way we check for differing node types

Categorized Under: Tech

Tagged As: Front End Web Development How It's Made javascript