トップページ > コンテンツ > プログラミング入門 > Ajax入門 > JavaScript入門 > HTML5 > WebComponents

Custom Elements

独自のhtmlタグを生成できる。
命名ルールがあり、"xxx-xxx"形式でないといけない。
var sample = Object.create(HTMLElement.prototype);
sample.createdCallback = function() {
   //生成時のコールバック。動きを規定。
   //(例)
   //this.innerHTML = "hoge";
}
var test = document.registerElement('xxx-xxx',{prototype: sample});

shadow Dom

通常のDOM操作ではアクセスできない境界を作り、カプセル化を行う技術の模様。
var shadow = this.createShadowRoot(); //shadow-rootが生成される。
shadow.innerHTML = "sample"; //ここでappendChildとtemplateを利用することで、テンプレートの内容をshadow DOMに適用することも可能。

templateタグ

レンダリングされないテンプレート作成用のタグ。
javascriptで一々createElement等を行わなくても
html形式のタグでテンプレートを記述しておける。

/*html*/
<template id="test">
 テンプレート内容を記述
 <content></content>
</template>

/*script*/
var template = document.querySelector('#test');
var clone = document.importNode(template.content, true); //cloneにtemplate内容を格納。

HTML imports

htmlを部品として、組み込む方法。
templateタグ等はhtml上に書くことになるので、別ファイルに切り出して
htmlインポートを使うと便利。
templateタグを別のhtmlでインポートすると、上の記述は以下のようになる。

/*html*/
<link rel="import" href="./テンプレートを記述した.html">

/*script*/
var content = document.querySelector('link[rel="import"]').import;
var template = content.querySelector('#test');
var clone = document.importNode(template.content, true); //cloneにtemplate内容を格納。

上記を全てを適用すると…

以下のような感じになる。
/*テンプレートhtml*/
<template id="test">
 <style>
   p {
       color: red;
   }
 </style>
 <p><content></content>
</template>

/*script*/
$(function() {
   var sample = Object.create(HTMLElement.prototype);
   sample.createdCallback = function() {
       var shadow = this.createShadowRoot(); //shadow-rootが生成される。
       var content = document.querySelector('link[rel="import"]').import;
       var template = content.querySelector('#test');
       var clone = document.importNode(template.content, true);
       shadow.appendChild(clone);
   }
   var test = document.registerElement('xxx-xxx',{prototype: sample});
});

/*適用先html*/
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="jquery-1.10.2.js"></script>
    <script src="script.js"></script>
    <link rel="import" href="./テンプレート.html">
</head>
<body>
  <xxx-xxx>テスト</xxx-xxx> 
</body>
</html>


最終更新:2015年06月13日 20:29