Why Templates

Permalink to "Why Templates"

Using innerHTML and template literal strings with no sanitization may cause security issues with script injection. In the past, developers used various workarounds to implement HTML templates, but all of these workarounds had issues.

This is where the <template> element comes in; templates provide truly inert DOM, a highly performant method to clone nodes, and reusable templating.

Using Templates

Permalink to "Using Templates"

Next, transition the component to use HTML Templates:

index.html

Permalink to "index.html"

Here you moved the DOM content into a <template> tag in the main document's DOM. Now refactor the custom element definition:

rating-element.

Permalink to "rating-element."

To use this <template> element:

  1. Query the template.
  2. Get its contents.
  3. Clone those nodes with templateContent.cloneNode
  4. Initialize the dom with the data.

Congratulations, now your web component's DOM is encapsulated, but the DOM is still static. In the next steps, you'll add support for updating the rating.