My Relationship With the DOM
I just love playing with JavaScript code that generates or manipulates the DOM. If you’re reading this and wondering, ‘what is the DOM?’, fear not. It is simply a tree of JavaScript objects that represents an HTML document.
I personally have a weird secret obsession with creating alternative ways to make reactive application drivers using the DOM (you know, like React, Vue, Angular, Svelte, etc.). I have written about it a few times, in fact. There are bunches of approaches to creating a DOM from code:
- The Virtual DOM — pioneered by React, virtual DOMs are fast because all the updates are done in tiny objects that virtually represent the DOM, hence Virtual DOM. In an update, both the previous and next virtual DOM objects are compared through a method known as diffing, and at the end of the process the new HTML is finally patched in. The thing that VDOMs tend to bring into play, however, are larger frameworks and therefore slower initial loads.
- Procedural DOM — many frameworks that rely on template languages/markup are actually processing that markup and building a procedural DOM, which simply builds up the DOM by parsing the given template into a set of procedural instructions. Template-language-based frameworks also tend to be large and thus have slower initial loads.
- Compiled DOM — frameworks like Svelte compile their template language in to very fast vanilla JS. This is an incredibly novel approach, it’s fast, and it works really well. However, you’d need to parse a whole language in order to create a DOM-compiling program. This will likely have both smaller file sizes and, therefore, faster loads. But, because of the complexities of designing and implementing a domain-specific language, for our project this solution is out of the question.
- Native DOM — this is the true vanilla way.
document.createElement(’sometag’)
is how we instantiate DOM elements, creating some fairly hefty objects. But, with all the advances of modern JS engines a lot of unused code actually gets dropped as ‘dead code’, so this is actually likely to be fairly to very fast. And at the very least, if you’re not…