217 points · by palmfacehn · 1y ago · 86 comments
I wrote some boilerplate JS, yes, but I have complete control over my frontend, and I understand how it works, and I don't need to compile it.
Anyway, it works well so far! The <template> tag is a great way to lay out components and then fill them in with simple JS functions.
One nuance is documented in my code comments:
// Ohhhhhh wow, we need to use firstElementChild when cloning the content of a template tag (!!!!):
// https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/template#avoiding_documentfragment_pitfalls
// I spent way too long on this.
const elem = $(tplSelector);
if (!elem) return;
return elem.content.firstElementChild.cloneNode(true);
Once I figured that out, it's been smooth sailing and very powerful.Oh, but I haven't cleaned up my code at all yet because I was just experimenting/hustling, so it's a bit spaghetti :) If you go looking, don't mind the mess.
---
[0]: https://github.com/timelinize/timelinize - a self-hosted application for bringing together all your data on your own computer and organizing it onto a single timeline: social media accounts, photo libraries, text messages, GPS tracks, browsing history, and more. Almost ready for its debut...
Template contents are in a separate document from the main document, which is what makes them inert. importNode() adopts the nodes into the document so they have the correct prototype immediately (which includes custom elements). Otherwise the adopt steps are run when the elements are first attached to the document, which adds another tree walk to the insert/append operation that costs some time.
So:
document.importNode(elem.content, true);
Then you'll have a DocumentFragment you can pull nodes out of. Or just append the whole fragment.Update: I'm using importNode() now -- works great too.
Regarding the gpx support... Don't want to lead you astray, but, have you seen https://www.sethoscope.net/heatmap/?
I haven't seen that, actually -- looks very nice. We do render a heatmap already, but I'm learning that heatmaps are very tricky to tune to be most useful/interesting. I will try to learn from that project.
Yeah, Lit's tagged template literals and render() method are basically a shorthand for making a <template> element, marking the spots where expressions go, cloning the template, then filling in those sports.
I'm really looking forward to Temporal [0] reaching a larger baseline. Between that and a lot of recent Intl pieces we are so close to not needing libraries for much of anything datetime related.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
It supports just about all the Date math, comparison, and calendar conversion you could ever want. It has nice toLocaleString() formatting options. It's built on immutable objects to avoid a whole class of bugs with the current JS Date.
I use libraries everywhere, for JS/TS this is luxon (now that the type hinting works) and arrow in Python. I do not even try to deal with dates or times directly.
Hey, and thanks for Caddy!
Still highly unstable between versions, but for being free, it looks really good and is very flexible. I've been pleased with it for this project.
At this point I've been ditching almost every other type of layout (Bootstrap's Grid, Flexbox, etc) in most places for just "vanilla" CSS Grid and I think it is fantastic. I think it is well worth learning if you haven't yet.
- The HTML
- The JS
- The CSS
In some sort of a structured way that's easy to load and distribute as a library. I don't like that to use webcomponents the right way, you have to load the logic from an import and then inline the html aspects of it.
There are userland single-file component projects, like my Heximal[2] project. Though Hexiaml specifically doesn't tackle the module format - it requires some kind of HTML Module polyfill.
I don't think the current situation is so bad though. The container format should mostly be irrelevant to consumers of a component. You need to import the component defintion whether that definition is in a .js file or .html file. Once you import it you use it the same.
There should be very few cases where the file format matters. Maybe for use when JS is turned off if HTML-based web components are considered safe to evaluate (their templates might expressive enough to potentially allow attacks).
[1]: https://github.com/WICG/webcomponents/issues/645
[2]: https://heximal.dev/ (Sorry the site is messed up on mobile. I need to fix it!)
You can also add script tags wherever you want. They will execute when added to the DOM, but they won't be scoped.
You might be thinking of shadow DOM: if you clone your template into a ShadowRoot, then any included styles will be scoped to that ShadowRoot.
I thought it was an optimization, but benchmarking `document.createElement` was significantly faster (firefox).
And then having `template` in your html means that changes to the template/use are less local.
I feel like this is an improvement that only makes sense if you're neck deep in the react world.
I don't know what your benchmarks were exactly, but my benchmarking (also primarily in firefox) shows cloning templates is much faster than `document.createElement` for many tree shapes I was encountering. (Not micro-benchmarks of one element or so at a time, but the tree contents of entire components and "pages" at a time.) That's before learning of a performance tweak I'd missed from reading this thread today (`document.importNode` for template contents cloning to avoid multiple tree walking passes to attach the clone to the document).
Maybe a more understandable example for you would be it's use in conjunction with <slot>, shown here: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/...
Another reason I like <template> is the ease of prototyping. A very straightforward approach is to mock up your HTML+CSS with placeholders of what your populated elements might look like. Instead of translating that into JS element generation code, you can simply remove the populated data and enclose the barebones element in a <template> tag.
Back in JS, you might have a simple initializer to add these elements as needed and a function to (re)populate them.
Simple, to the point and no libraries or frameworks required.
There are a few modern libraries and frameworks that trend in this direction: Nue, Datastar, Lit. The DX and UX with these is a breath of fresh air.
I've experimented with this approach myself with Miu[1]. It doesn't quite integrate with Web Components nicely yet, but it's almost there. I have some bones to pick with the WC standard, but that's a separate matter.
My wish is that modern web development can eventually not require any 3rd party libraries or frameworks, just like in the early days. Web developers got used to these because of limitations of native web APIs, but the web has grown leaps and bounds since then. Before the modern workflow became standard, it was magical to open a text editor, and have a functioning web page within a few minutes. No dependencies, no build step, no nonsense. Let's bring that back, please.
The time is right for a DOM templating API: https://justinfagnani.com/2025/06/26/the-time-is-right-for-a...
What should a native DOM templating API look like?: https://justinfagnani.com/2025/06/30/what-should-a-dom-templ...
There are plenty of ways HTML templating can be done already using JavaScript. The simplest approach of using tagged template literals, as you mention, doesn't even require external dependencies.
The problem with this approach is that it makes JavaScript a requirement for all but static sites, and those doing templating on the server. This shouldn't be the case.
The web as a platform should be flexible, and provide tools to build maintainable web sites and applications without forcing developers and users to depend on a specific runtime. JS should be an optional dependency, just like CSS is today. Even HTML should be optional, as Web Assembly gains traction, and the web browser becomes a software delivery platform.
Furthermore, making what should be a core HTML feature depend on JS is a colossal violation of separation of concerns. HTML modules should be a standalone feature, and we should be able to define a tree of HTML modules, import modules, reuse them, and so on. That should be the core groundwork on top of which templating is built on.
We've had Server-Side Includes and XSLT since the 90s, yet HTML templating should depend on JS? That's just silly.
Besides, there's a strong argument to be made for minimizing logic in templates or avoiding it altogether. Mustache and Handlebars have shown that this can work simply and elegantly. Whenever I see JS inside HTML attributes, I curse whoever came up with the idea. It's awful for legibility, maintainability, and plain sanity.
HTML can be a lot more capable without having to depend on JS. I think the discussion to drive this implementation forward would be well served by first principles thinking, instead of being inspired by modern web frameworks and JavaScript features.
But there's just something about this type of binding that makes me want to give it a serious chance, at least once, before completely giving up on it.
[1]: https://github.com/flatiron/plates
[2]: https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Mic...
If you listen to people actually building frameworks (Solid, Preact, Vue, Svelte), you'll learn that "modern web features" have very few actual features that make development easier. All frameworks would absolutely love if they could replace "bloated abstractions" with actual built-in browser features. Too bad, all of those features are built in complete isolation from what anyone but a very small group of Chrome devs want.
> Web developers got used to these because of limitations of native web APIs, but the web has grown leaps and bounds since then.
It hasn't. At least not in the direction you want.
> No dependencies, no build step, no nonsense. Let's bring that back, please.
Nothing stops you from doing that now.
That depends on the subjective definition of "easier", but most of these frameworks use abstractions that are too complex and not worth the value they deliver. They ironically make development more difficult, since there are more moving parts, more concepts to understand, and more things to break, which in turn makes the user experience much, much worse.
The entire idea of writing fake HTML that gets parsed, compiled, and interpreted in JavaScript to manipulate the DOM at runtime is wrong. The concept of a virtual DOM, diffing, reconciliation, and a bunch of related nonsense, is wrong. The insanity of an entire ecosystem of tools built around solving client-side state management. The trend of moving everything, including CSS, to be interpreted in JS is insane. Abstractions like Tailwind that shouldn't exist in the first place, which are then further abstracted away by abominations like daisyUI. The numerous frameworks that promise to blur the line between frontend and backend development, only to fall flat on their face when the insanity of the approach becomes apparent, but not before amassing a significant user base in the process. The fact most web developers have accepted that 100MB+ of dependencies are required to show a "Hello World!" in a web browser. The idea that every web site must be a SPA, and the numerous hacks around that to make it work like a traditional web site. I could go on, and on...
The popularity of these tools and ideas is not an indication that they lead to a sane, let alone optimal, development environment. It just means that the field has become dominated by influencer developers, to the point that junior developers entering the field are not aware of other ways of building web applications. After all, React and Vue stand out in a CV much more than JavaScript. It's practically unheard of to be considered a web developer without having one of these frameworks under your belt, so it becomes a reinforcing loop.
> It hasn't. At least not in the direction you want.
That's not true. JavaScript in web browsers is a stable, modern language. HTML has received numerous transformative updates over the years, such as the `template` element we're discussing here. The evolution of CSS has been mind-boggling, and difficult to keep track of. Gone are the cross-browser quirks and incompatibilities, which is mostly due to Google dominating the web, but that's beside the point. Web servers have become more flexible and easier to deploy. And so on.
Frameworks like Datastar prove that web development can be much simpler, and deliver better user experiences in a fraction of the complexity of traditional frameworks. This is not because it reinvents the same abstractions used elsewhere, but because it takes a first principles approach and rejects building on top of the existing pile of abstractions. It leverages proven technologies such as Server-Sent Events, and doesn't reinvent the wheel. If you've seen the demos and examples, the results speak for themselves.
It's not difficult to imagine a similarly simplified workflow becoming standard across web clients and servers. All it would take is an industry-wide push to bring all existing technologies together in a cohesive package. We're not technically far from that, so frameworks like Datastar are still needed, but we definitely don't need the bloated frameworks of yore.
Because there's nothing in the web standards to do it otherwise.
> The concept of a virtual DOM, diffing, reconciliation, and a bunch of related nonsense, is wrong.
Of the frameworks I mentioned none use virtual DOM or diffing. They have all moved to a much more efficient way that is, guess what, on a way to become a native browser standard: https://github.com/tc39/proposal-signals
> The insanity of an entire ecosystem of tools built around solving client-side state management.
Any time you have a dynamic UI, you have state management. I wish the web remained static, but that ship has sailed long ago. And there's nothing in web standards that helps with state management.
> It just means that the field has become dominated by influencer developers, to the point that junior developers entering the field are not aware of other ways of building web applications.
It's strange how you completely dismissed Solid, Vue, and Svelte which all offer a different way to build web apps when compared to React, for example.
> JavaScript in web browsers is a stable, modern language.
You need more than just a language. You also need libraries and actual useful functionality exposed by the browsers.
Literally the whole reason so many libraries and frameworks have popped over the years, is because no one wants to spend time writing hundreds of lines of code just to properly set up and change some DOM element. And the reason very few libs/frameworks (even newcomers) use "the amazing new features in the browsers" is because these features have a list of features issues and caveats a mile long. Here's just one single example: https://x.com/Rich_Harris/status/1841467510194843982
> HTML has received numerous transformative updates over the years, such as the `template` element we're discussing here.
And what, pray tell, does template give you? On its own it's useless. You need some JS to manipulate it, at least.
> but because it takes a first principles approach and rejects building on top of the existing pile of abstractions.
Didn't you just say this: "The entire idea of writing fake HTML that gets parsed, compiled, and interpreted in JavaScript to manipulate the DOM at runtime is wrong. "?
What do you think Datastar is doing if not literally the same thing. How do you think this works:
<div data-signals="{counter: 0, message: 'Hello World', allChanges: [], counterChanges: []}">
<div class="actions">
<button data-on-click="$message = `Updated: ${performance.now().toFixed(2)}`">
Update Message
</button>
<button data-on-click="$counter++">
Increment Counter
</button>
<button
class="error"
data-on-click="$allChanges.length = 0; $counterChanges.length = 0"
>
Clear All Changes
</button>
</div>
<div>
<h3>Current Values</h3>
<p>Counter: <span data-text="$counter"></span></p>
<p>Message: <span data-text="$message"></span></p>
</div>
<div
data-on-signal-patch="$counterChanges.push(patch)"
data-on-signal-patch-filter="{include: /^counter$/}"
>
<h3>Counter Changes Only</h3>
<pre data-json-signals__terse="{include: /^counterChanges/}"></pre>
</div>
<div
data-on-signal-patch="$allChanges.push(patch)"
data-on-signal-patch-filter="{exclude: /allChanges|counterChanges/}"
>
<h3>All Signal Changes</h3>
<pre data-json-signals__terse="{include: /^allChanges/}"></pre>
</div>
</div>
It does (ab)use the browser for the preliminary parsing, but then it does what everyone else does (only probably worse). E.g. by literally parsing attribute contents to reimplement half of Javascript for "reactive expressions": https://github.com/starfederation/datastar/blob/develop/libr...But the big problem that template tries to solve is building DOM fragments that are parsed but not "live" in the open documment. Before the template tag there was no good way to do that other than JS and createElement/createElementNS, and that has always been slower than the Browser's well optimized HTML parser.
Also, the slot tag does solve a minor problem of being the first tag whose out-of-the-box (browser CSS) behavior is `display: contents;`. It's obviously not a huge lift from the CSS one-liner, but there are still some uses for it even outside of templates.
I guess maybe slots for web components is the other point?
This worked pretty well but definitely had some rough edges which I really wish the standards process could’ve focused on. Things like JSX are so much slower / memory intensive but people use them for convenience and it’d be nice to improve the ease-of-use story.
Largely, I think. Though I've not got around to actually using them yet myself, so take my understanding with a pinch of salt.
Compared to doing that with non-displayed HTML tags outside a template there are performance benefits (the parser deals with it differently knowing it isn't intended to be an active bit of DOM yet) and convenience benefits (IIRC the contents are not going to be picked up by querySelector/querySelectorAll).
Compared to building document fragments in JS they can be a lot more convenient to create and edit, and keep your design and code less tightly coupled (so a designer on your team who doesn't want to touch JS (or who you don't want messing with your JS!) can easily play with them to a certain extent). Other methods to achieve the same separation may involve an extra build step in deploying your work.
Which is a simpler way of thinking about templates, rather than slots and fragments.
<script> parses its contents as text, whereas <template> parses as DOM. This means you don't have to escape `<`, just `</script>`.
Myself and some browser engineers been working on proposals to allow for inline modules, including JSON, that are importable into other modules via regular import statements.
This is why I recommend the "-json" type - so it doesn't collide with a future native "json" type.
I wouldn't use application/json just in case browsers start supporting that and it has different semantics than whatever custom thing you might do, causing a webcompat issue when the native feature rolls out.
Although with JSON, it's pretty unlikely that there would be any differing semantics. JSON modules in JS are just JSON blocks with no special additions and no named exports. That's what inline versions would be as well.
Isn’t everything just JSON, CSS, JavaScript, and a whole lot of DIV and SPAN elements?