The Anatomy of a Web Component: HTML Templates


placeholder

This is a premium lesson.

Subscribe to get access to the entire course.

Sign up now

The template element is an HTML element unlike any other. For starters, the browser won’t render a template element on page load. Nothing would get rendered if you were to the run the following HTML in the browser:

<body>
	<template id="template">
		<p>Copyright <span class="year"></span>, <span class="name"></span></p>
	</template>
</body>

This is a feature and not a bug. Instead of rendering to the page, the template element exists for other prospective elements to clone it and render the clone. You can think of it like the schematics for an object ready to be 3D printed. The design itself isn’t a tangible thing, but the printer uses it to create a physical copy.

All of the content within the template is in a kind of inert state. The browser knows it exists, but things like the CSS in a style element won’t alter the appearance of the page. Images are similarly affected, in that they won’t load until the template is used in the page.

To use a temp