Include another HTML file in a HTML file
HTMLファイルに別のHTMLファイルを含める
<iframe>
要素を使うと、別のHTMLファイルを現在のページ内にフレームとして表示することができます。
<iframe src="other.html"></iframe>
上記のように記述すると、other.html
が現在のページ内に表示されます。
利点:
- 実装が簡単
- 別のHTMLファイルのコンテンツを動的に更新できる
- スクロールバーが表示される
- デザインが制限される
<object>
要素を使うと、別のHTMLファイルを埋め込むことができます。
<object data="other.html"></object>
- デザインを自由に変更できる
- 実装が複雑
- 古いブラウザではサポートされていない
サーバーサイドインクルードを使うと、別のHTMLファイルをサーバー側で処理して、現在のページに含めることができます。
例:
- 処理速度が速い
- サーバーの設定が必要
<div id="content"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "other.html");
xhr.onload = function() {
document.getElementById("content").innerHTML = xhr.responseText;
};
xhr.send();
</script>
- 柔軟性が高い
HTMLファイルに別のHTMLファイルを含める方法はいくつかあります。それぞれの方法には利点と欠点があるので、目的に合った方法を選択する必要があります。
<iframe> 要素を使う
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
<iframe src="other.html"></iframe>
</body>
</html>
<object> 要素を使う
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
<object data="other.html"></object>
</body>
</html>
サーバーサイドインクルードを使う
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
</body>
</html>
JavaScriptを使う
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
<div id="content"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "other.html");
xhr.onload = function() {
document.getElementById("content").innerHTML = xhr.responseText;
};
xhr.send();
</script>
</body>
</html>
実行方法
<iframe> 要素を使う
- 上記のサンプルコードを
index.html
という名前で保存します。 other.html
という名前で別のHTMLファイルを作成します。- ブラウザで
index.html
を開きます。
<object> 要素を使う
サーバーサイドインクルードを使う
- Webサーバーの設定で、サーバーサイドインクルードを有効にします。
JavaScriptを使う
注意事項
- サーバーサイドインクルードを使う場合は、Webサーバーの設定が必要です。
- JavaScriptを使う場合は、ブラウザが JavaScript をサポートしている必要があります。
HTMLファイルに別のHTMLファイルを含める他の方法
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
<link rel="stylesheet" href="other.html">
</head>
<body>
<h1>This is the main page</h1>
</body>
</html>
- 読み込み速度が速い
- スタイルシートしか読み込めない
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
<script src="other.html"></script>
</body>
</html>
- JavaScript を実行できる
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Include another HTML file</title>
</head>
<body>
<h1>This is the main page</h1>
<div id="content"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "other.html");
xhr.onload = function() {
document.getElementById("content").innerHTML = xhr.responseText;
};
xhr.send();
</script>
</body>
</html>
- ページ全体の読み込み速度が速くなる
javascript html dom