Hacker News new | ask | show | jobs
by baybal2 2824 days ago
One thing I was finding weird about all those template compiling frameworks is the use of javascript for parsing the page/template instead of the lightning fast browser's native parser (DOMParser)

Can somebody shed some light on that design decision?

5 comments

There are other approaches: Svelte compiles directly to DOM operations, choo/Marko use the native parser through morphdom, hyperhtml and lit-html use string literals and Template instances. Most of them are faster than React and Vue but nowhere as popular.
Virtual DOM tends to be faster because bridging between JS and native layers can be expensive. If diffing is done in the JS layer, some potentially expensive calls can be batched or ignored if a change is unnecessary.
I mean why they use it at the stage when they create their own virtual DOM copy from the template string, not during the time they do changes when the app is running.
IMO, with Vue if your template needs to be parsed in-browser, you're doing something wrong (Vue has "full" and "runtime-only" builds; I don't think that you should use the full build in production). The template should be parsed+compiled to a render() function during the build process, and the browser should only ever see the render() function, not the template (except through a source-map).
Using DOMParser means parsing the template twice, once for DOMParser and once for your template syntax, making perf gains more questionable. Also, doing HTML and template parsing separately means either passing template syntax through the HTML parser, which limits possible template syntax and spends time instantiating bogus DOM elements/attributes, or passing HTML through a HTML-unaware templating language, creating all the problems and limitations of C’s #define and making it hard to react to data changes with minimal updates.

That said, it’s been done both ways. Mustache templates do string templating then use the native HTML parser, and one smaller library, I don’t remember which, parses the template as HTML then tree walks for templating controls, and cites perf benefits.

Vue 1 used to do that.

It caused issues, specifically, the svg attributes are camelCased and DOMParser would convert them to lowercase when used with v-bindings. So, Vue2 come up with its own parser to mitigate the issue.