简单介绍HTML5中的文件导入

2020-04-21 07:51:26易采站长站整理

<script src="js/script2.js"></script>     // 3.  

1.在index.html 中加载component.html并等待执行

2.执行component.html中的script1.js

3.执行完script1.js后执行component.html中的script2.js

4.执行完 script2.js继而执行index.html中的script3.js

注意,如果给link[rel="import"]添加async属性,HTML导入会把它当做含有async属性的脚本来对待。它不会等待HTML导入文件的执行和加载,这意味着HTML 导入不会妨碍HTML主文件的渲染。这也给提升网站性能带来了可能,除非有其他的脚本依赖于HTML导入文件的执行。
跨域导入

从根本上说,HTML导入是不能从其他的域名导入资源的。

比如,你不能从http://webcomponents.org/向 http://example.com/ 导入HTML 文件。为了绕过这个限制,可以使用CORS(跨域资源共享)。想了解CORS,请看这篇文章。
HTML导入文件中的window和document对象

前面我提过在导入HTML文件的时候里面的脚本是会被执行的,但这并不意味着HTML导入文件中的标签也会被浏览器渲染。你需要写一些JavaScript代码来帮忙。

当在HTML导入文件中使用JavaScript时,有一点要提防的是,HTML导入文件中的document对象实际上指的是HTML主文件中的document对象。以前面的代码为例,index.html和  component.html 的document都是指index.html的document对象。怎么才能使用HTML导入文件中的document 呢?借助link中的import 属性。

index.html
 

XML/HTML Code复制内容到剪贴板

var link = document.querySelector(‘link[rel="import"]’);   
link.addEventListener(‘load’, function(e) {   
  var importedDoc = link.import;   
  // importedDoc points to the document under component.html   
});  

为了获取component.html中的document 对象,要使用document.currentScript.ownerDocument.

component.html
 

XML/HTML Code复制内容到剪贴板

var mainDoc = document.currentScript.ownerDocument;   
// mainDoc points to the document under component.html  

如果你在用webcomponents.js,那么就用document._currentScript来代替document.currentScript。下划线用于填充currentScript属性,因为并不是所有的浏览器都支持这个属性。

component.html

 

XML/HTML Code复制内容到剪贴板

var mainDoc = document._currentScript.ownerDocument;   
// mainDoc points to the document under component.html   

通过在脚本开头添加下面的代码,你就可以轻松地访问component.html中的document对象,而不用管浏览器是不是支持HTML导入。