Hello World 示例

此示例将自定义元素,模板,Shadow DOM 和 HTML 导入组合在一起,以显示 Hello World! HTML 中的字符串。

在档案 hello-world.html

<!-- 1. Define the template -->
<template>
   Hello, World!
</template>

<script>
  var template = document.currentScript.ownerDocument.querySelector( 'template' )   

  //2. Define the custom element
  
  customElements.define( 'hello-world', class extends HTMLElement 
  {
      constructor() 
      {
          //3. Create a Shadow DOM
          var sh = this.attachShadow( { mode: 'open' } )
          sh.appendChild( document.importNode( template.content, true ) )
     }
  } )
</script>

在主文件 index.html 中:

<html>
<head>
    <!-- 4. Import the HTML component --> 
    <link rel="import" href="hello-world.html">
</head>
<body>
    <hello-world></hello-world>      
</body>
</html>