[HTML] <template>要素について

2 min read
hiroweb developer

template 要素とは

HTML のコンテンツテンプレート (<template>) 要素 は、すなわちページの読み込み時にすぐには描画されないものの、後で JavaScript を使用してインスタンスを生成できる HTML を保持するメカニズムです。

テンプレートは、文書内に格納されたコンテンツの断片として考えてください。ページの読み込み時にパーサーが <template> 要素の内容を処理している間、その内容の有効性のみが検証されます。しかし、要素の内容は描画されません。

developer.mozilla.org<template>: コンテンツテンプレート要素 - HTML: ハイパーテキストマークアップ言語 | MDN<template> は HTML の要素で、ページが読み込まれたときにすぐにレンダリングされるのではなく、実行時に JavaScript を使って後からインスタンス化することができる HTML を保持するためのメカニズムです。

template 要素の特徴

  1. コンテンツは DOM に展開されるまで動作しない
    → メモリー上に存在するだけでレンダリングされない
  2. <template>内のコンテンツは反応しない:
    1. <script>は動作しない
    2. <img>の読み込みは発生しない
    3. <audio>は再生されない
      などなど…
  3. <template>内のコンテンツは DOM ツリー状に存在しないため、document.getElementById()querySelector() で取得することが出来ない

https://web.archive.org/web/20220615032437/https://www.html5rocks.com/ja/tutorials/webcomponents/template/

使い方

<template class="template-element">
  <img src="//example.com/image.png" alt="sugoi gazou" />
</template>
// <template>要素から取得
const template = document.querySelector('.template-element');
const clone = document.importNode(template.content, true);
const img = clone.querySelector('img');

// DOMツリーへの挿入
document.body.appendChild(img);

その他

<template>
  <div>
    <template>
      <div>inner template</div>
    </template>
  </div>
</template>

外側のtemplateをアクティベートしても、内側のtemplateはアクティベートされない。