var content = document.querySelector('link[rel="import"]').import;
在下面几种情况下,link.import 值为 null :
浏览器不支持 HTML 导入。
没有 rel=”import”。
没有被加入到 DOM 中。
从 DOM 中被移除。
资源没有开启 CORS。
实例
假设 warnings.html 包含如下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<divclass="warning"> <stylescoped> h3 { color: red; } </style> <h3>Warning!</h3> <p>This page is under construction</p> </div>
<divclass="outdated"> <h3>Heads up!</h3> <p>This content may be out of date</p> </div>
导入页面中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<head> <linkrel="import"href="warnings.html"> </head> <body> ... <script> var link = document.querySelector('link[rel="import"]'); var content = link.import; // 从 warning.html 的文档中获取 DOM。 var el = content.querySelector('.warning'); document.body.appendChild(el.cloneNode(true)); </script> </body>
包含模板
HTML Template 元素是 HTML 导入的好搭档。
import.html
1 2 3 4 5
<template> <h1>Hello World!</h1> <imgsrc="world.png"><!-- 只有当模板生效后才会去请求图片 --> <script>alert("Executed when the template is activated.");</script> </template>
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<head> <linkrel="import"href="import.html"> </head> <body> <divid="container"></div> <script> var link = document.querySelector('link[rel="import"]'); // 从导入中复制 <template>。 var template = link.import.querySelector('template'); var content = template.content.cloneNode(true) document.querySelector('#container').appendChild(content); </script> </body>