HTML Template
HTMLから別ファイルのテンプレートを読み込む最もシンプルな方法
- 標準機能のみ
- ライブラリ不要
HTML index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<style>
body {
  width: 35em;
  margin: 0 auto;
  font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
<script defer="" src="loader.js"></script>
</head>
<body>
<h1>An error occurred.</h1>
<div>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</div>
<div id="template-header"></div>
<div><em>You be peaceful.</em></div>
</body>
</html>
HTML template template.html
<template id="inline-header">
  <div><h2>Internal server failed to eat spice curry.</h2><div>
</template>
JavaScript loader.js
class Loader {
  action() {
    const templates = document.querySelectorAll('div[id^=template-]');
    templates.forEach(template => {
      const inline = template.id.replace(/template/, 'inline');
      const fragment = document.querySelector(`#${inline}`);
      template.append(fragment.content);
    });
  }
  trigger() {
    fetch('template.html')
    .then(res => res.text())
    .then(content => {
      document.body.innerHTML += content;
      this.action();
    });
  }
}
window.addEventListener('DOMContentLoaded', () => new Loader().trigger());
このコードは、特定のアクションをトリガーとして実行される Loader クラスを定義しています。主な目的は、template.html からテンプレートを取得し、そのテンプレートをページの特定の場所に挿入することです。
説明
- 
Loader クラスは、テンプレートのロードとアクションの実行を担当します。 
- 
action() メソッドは、テンプレートをロードし、特定の要素に挿入する処理を行います。 
- 
querySelectorAll('div[id^=template-]') は、id 属性が "template-" で始まるすべての div 要素を取得します。つまり、id 属性が "template-" で始まる全ての div 要素がテンプレートの要素となります。 
- 
templates.forEach(template => { ... }) は、取得したテンプレートの要素ごとに処理を行います。 
- 
template.id.replace(/template/, 'inline') は、テンプレートの id 属性の "template" を "inline" に置き換えます。これにより、テンプレートの id から対応するインラインテンプレートの id を生成します。 
- 
document.querySelector(#${inline}) は、生成されたインラインテンプレートの id を使用して、対応する要素を取得します。 
- 
template.append(fragment.content) は、取得したインラインテンプレートの内容をテンプレート要素に追加します。 
- 
trigger() メソッドは、テンプレートのロードとアクションの実行をトリガーします。 
- 
fetch('template.html') は、"template.html" を取得するための Fetch API を使用します。 
- 
.then(res => res.text()) は、レスポンスをテキスト形式で解析します。 
- 
.then(content => { ... }) は、解析されたテキストコンテンツを取得し、次の処理を行います。 
- 
document.body.innerHTML += content は、取得したテキストコンテンツを現在のページの HTML の末尾に追加します。 
- 
this.action() は、テキストコンテンツの追加後に action() メソッドを呼び出し、テンプレートのロードと挿入を実行します。 
- 
window.addEventListener('DOMContentLoaded', () => new Loader().trigger()) は、ページのコンテンツがすべて読み込まれた後に trigger() メソッドを呼び出します。これにより、テンプレートのロードと挿入が開始されます。 
テンプレートがシンプルになることに焦点を当てました。