3 ms·
<template> is special, very different from display: none; and definitely has a few advantages: - The elements in it are parsed into a different document and ar
by spankalee 4y ago
<template> is special, very different from display: none; and definitely has a few advantages:
- The elements in it are parsed into a different document and are inert until cloned or adopted into the main document. Images don't load, scripts don't run, styles don't apply, etc. This is very important.
- The content model validation is turned off, so a <template> can contain a <td>
- Mutation observers and events are not fired for parsed content.
- The <template> element itself can appear anywhere, including restricted content elements like <table>
- Other HTML processing libraries generally know to ignore <template>, unlike other content just hidden with CSS.
This makes parsing faster and guaranteed to have no side effects, and conveys the correct semantics to the browser and tools.
- tomhallett 4y agoIn addition - “template” also conveys correct semantics to the other developers working on the codebase. If I see an html at the bottom with “display: none” it’s very possible that the intended usage is to leave it there and set “display: block”, ie a modal. “display: none” doesn’t convey “clone me”, but “template” does.
- sgc 4y agoYou can use templates for simpler items as indicated in the linked article, but it seems like it would be best used for larger datasets. I would usually load those async to avoid blocking the page while they download. Does it provide practical advantages over loading html to a js object via fetch?