---
title: "HTML import"
author: "2008winstar"
date: "2014-12-09T21:21:22Z"
tags: []
categories: ["Web前端"]
slug: "html-import"
draft: false
lastmod: "2014-12-14T16:29:59Z"
id: 2164657
url: "https://2008winstar.iteye.com/blog/2164657"
---

&lt;link rel="import" href=""&gt;

1、使用link标签导入

2、link标签的rel属性值为import

3、link标签的href属性值为需要导入的资源

```
<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
        <link rel="import" href="imports/myimport.html">
    </head>
    <body>
        <p>This is a import demo</p>
    </body>
</html>
```

 

 

import关键字给资源提供的默认类型是text/html

该link标签还有一个async属性，其值为布尔类型

该link标签不依赖media属性（media属性不生效）

 

可以在JavaScript中获取到import的属性，如

```
var link = document.querySelector('link[rel=import]');
var heart = link.import;
var pulse = heart.querySelector('div.pulse');
```

 

返回的import为被引入的文档的document对象。

 

如果通过JavaScript脚本创建link import标签，可以通过onload或onerror事件监听其是否加载成功或失败，如

```
var link = document.createElement('link');
link.rel = 'import';
link.href = 'myimport.html';
document.head.appendChild(link);
alert(link.import) // null，因为import的内容是异步载入，需要通过下面的onload来处理
link.onload = function(){};
link.onerror = function(){};
```

 

 虽然，返回的import为document对象，但导入的document不能使用document.open()，document.write()，document.close()方法，使用这些方法会抛出InvalidStateError异常。

 

由于是document对象，可以使用document.head.innerHTML;document.body.innerHTML;document.querySelector()

 

被导入的html文档中也隐含着head和body，其中导入其它文档（如果有的话）的link标签会出现在document.head中，其余的会出现在document.body中。

 

在被导入的html文档中的document指的是主文档的document；

在被导入的html文档中，可以通过document.currentScript.ownerDocument来获取当前（即被导入文档自身）的document

 

将被导入html文档的内容加到主文档的示例：

```
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Demo</title>
    <link rel="import" href="imports/myimport.html">
</head>
<body>
    <script>
        var link = document.querySelector('link[rel="import"]');
        document.body.appendChild(link.import.body.querySelector('p').cloneNode(true));
    </script>
</body>
</html>
```

 

 浏览器的网络协议栈（network stack）会对访问相同URL的请求自动去重。这意味着从同一个URL导入的内容只会被获取一次。无论这个地址被导入多少次，最终它将只执行一次。

 

特性检测：

```
function supportImports() {
    return 'import' in document.createElement('link');
}
```