<template>-Content Template
The <template>
tag is a native HTML5 element introduced to declare a content template. It is not directly rendered on the page but serves as a "container" for dynamically generating content with JavaScript. By combining it with JavaScript (e.g., cloneNode
or framework-specific template syntax), the template content can be efficiently reused.
Basic Characteristics of <template>
The content inside a <template>
tag is inert by default:
- Does not trigger resource loading (e.g.,
src
of<img>
) - Does not execute scripts (
<script>
) - Is invisible (
display: none
style) - Can be accessed via DOM APIs
<template id="user-card">
<div class="card">
<h2 class="username"></h2>
<p class="email"></p>
</div>
</template>
Differences from Regular DOM
Regular HTML elements are rendered immediately and trigger resource loading, while <template>
content remains "frozen":
<!-- Regular div renders immediately -->
<div id="live-content">
<img src="immediate-load.jpg"> <!-- Image loads immediately -->
</div>
<!-- Template content does not render -->
<template id="inert-content">
<img src="not-load.jpg"> <!-- Does not load -->
<script>alert('Will not execute')</script>
</template>
Activating Templates with JavaScript
Use document.importNode()
or cloneNode()
to activate template content:
const template = document.getElementById('user-card');
const content = template.content.cloneNode(true); // Deep clone
// Populate data
content.querySelector('.username').textContent = 'John Doe';
content.querySelector('.email').textContent = 'john@example.com';
// Insert into DOM
document.body.appendChild(content);
Integration with Web Components
<template>
is often used to define Shadow DOM content for Web Components:
class MyComponent extends HTMLElement {
constructor() {
super();
const template = document.getElementById('component-template');
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('my-component', MyComponent);
Dynamic Template Generation
Templates can be created dynamically using string concatenation or template literals:
// Dynamically create a template
const dynamicTemplate = document.createElement('template');
dynamicTemplate.innerHTML = `
<style>
.dynamic { color: red; }
</style>
<p class="dynamic">Dynamically generated content</p>
`;
document.body.appendChild(dynamicTemplate.content);
Template Optimization in Frameworks
Modern frameworks (e.g., Vue, React) may use <template>
under the hood for rendering optimizations:
<!-- Vue single-file component -->
<template>
<div>{{ message }}</div>
</template>
Browser Compatibility Notes
- IE does not support
<template>
at all. - Older versions of Edge require a polyfill.
- Modern browsers (Chrome/Firefox/Safari/Edge) fully support it.
Feature detection can be used to check support:
if ('content' in document.createElement('template')) {
// Template is supported
} else {
// Fallback solution
}
Performance Comparison Experiment
Compare the performance of direct DOM manipulation versus using templates:
// Direct DOM manipulation (slower)
function renderDirectly(items) {
const container = document.getElementById('container');
container.innerHTML = '';
items.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
container.appendChild(div);
});
}
// Using templates (faster)
function renderWithTemplate(items) {
const container = document.getElementById('container');
const template = document.getElementById('list-item-template');
container.innerHTML = '';
items.forEach(item => {
const content = template.content.cloneNode(true);
content.querySelector('div').textContent = item;
container.appendChild(content);
});
}
Complex Template Nesting
Templates can be nested for complex UI structures:
<template id="page-layout">
<header>
<slot name="header"></slot>
</header>
<main>
<template id="content-section"></template>
</main>
</template>
<template id="content-section">
<section class="posts">
<template id="post-item"></template>
</section>
</template>
CSS Scoping in Templates
Styles inside templates do not affect the external DOM by default but take effect upon activation:
<template id="styled-template">
<style>
/* Will affect the DOM where it is inserted after activation */
p { color: blue; }
</style>
<p>Blue text</p>
</template>
Server-Side Rendering Applications
In Node.js environments, templates can be processed using jsdom
:
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`
<template id="server-template">
<p>Server-generated template</p>
</template>
`);
const template = dom.window.document.getElementById('server-template');
console.log(template.innerHTML); // Output template content
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:<slot>-Web组件插槽