LoginSignup
2
2

More than 5 years have passed since last update.

HTML Importsをwebcomponentsjsで実装

Last updated at Posted at 2015-12-19

はじめに

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>

こんな感じ
スクリーンショット 2015-12-19 20.50.58.png

  • <link rel="import" href="child.html">child.htmlはロードされるけど、DOMに追加するのはJSでやらないといけない。
  • <link rel="import" href="child.html">の前にCSSを書いちゃうと、child.htmlにCSSが反映されない。
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2