8 Working with Templates and Slots
This chapter covers
- Using
<template>elements for components - Working with external HTML files
- Rendering dynamic data in your templates
- Projecting content to components using
<slot>
So far, we’ve been loading HTML content inline in our web components' JavaScript using innerHTML or the DOM APIs. But as we grow our application and the complexity of our web components increases, this solution may no longer be ideal. In this chapter, we will cover several techniques we can use to improve performance, developer experience, and the organization of our web component’s markup, starting with the Template Content HTML element.
8.1 The Template Content HTML Element
The <template> element provides a declarative way to define chunks of markup that are not immediately rendered when the browser parses them. The content is parsed but not executed, which means no images or stylesheets referenced in the markup will be loaded, and no scripts will be executed until we actually use them. To use it, we will clone it and attach the clone to the DOM.
Anything placed inside a <template> lives in a separate DocumentFragment and is ignored during initial page rendering. A Document Fragment is a lightweight, "off-screen" DOM container containing nodes that are not part of the page’s live DOM.