はじめに
Webページのヘッダーやフッターを記述するファイルを分けたいと思ったので、HTML Importsを試してみることにした。
Webcomponentsjsのダウンロード
クローン
git clone https://github.com/webcomponents/webcomponentsjs.git
ビルド
npm install
gulp build
ビルドできたので、webcomponentsjs/dist/HTMLImports.min.js
を使う。
HTML Importsを試す
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="content-language" content="ja">
<title>Test page for Html imports</title>
<script type="text/javascript" src="HTMLImports.min.js"></script>
<link rel="import" href="child.html">
<style type="text/css">
html{
margin: 0;
padding: 0;
}
body{
margin: 0;
padding: 0;
}
section{
margin: 20px;
padding: 5px 20px;
background-color: #eee;
border-radius: 8px;
}
section.child{
margin: 20px;
padding: 5px 20px;
background-color: #FF6E40;
border-radius: 8px;
}
</style>
</head>
<body>
<section>
<h1>HTML Imports</h1>
<p>このセクションはindex.html</p>
</section>
<!-- import here -->
<div id="import-wapper"></div>
<script type="text/javascript">
var imports = document.querySelector('link[rel=import]').import;
var child = imports.querySelector('div#import-inner');
if(child){
var parent = document.querySelector('#import-wapper');
parent.appendChild(child);
}
</script>
</body>
</html>
child.html
<div id="import-inner">
<section class="child">
<h1>Child</h1>
<p>これはchild.html</p>
</section>
</div>
-
<link rel="import" href="child.html">
でchild.html
はロードされるけど、DOMに追加するのはJSでやらないといけない。 -
<link rel="import" href="child.html">
の前にCSSを書いちゃうと、child.html
にCSSが反映されない。