Home  >  Article  >  Web Front-end  >  A brief introduction to file import in HTML5_html5 tutorial skills

A brief introduction to file import in HTML5_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:46:411489browse

Template, Shadow DOM and Custom Elements make it easier than ever to create UI components. But resources like HTML, CSS, and JavaScript still need to be loaded one by one, which is very inefficient.

Removing duplicate dependencies is not simple either. For example, loading jQuery UI or Bootstrap now requires adding separate tags for JavaScript, CSS, and Web Fonts. If your web component applies multiple dependencies, things get more complicated.

HTML import lets you load these resources as a combined HTML file.
Import using HTML

To load an HTML file, you need to add a link tag whose rel attribute is import and herf attribute is the path of the HTML file. For example, if you want to load component.html into index.html:

index.html

XML/HTML CodeCopy content to clipboard
  1. <link rel="import" href="component.html" >

You can import files into HTML (Translator’s Note: This article translates “the imported HTML” as “HTML import file” and “the original HTML” as “HTML main file”. For example, index.html is HTML The main file, component.html is the HTML import file.) Add any resources, including scripts, style sheets and fonts, just like adding resources to ordinary HTML.

component.html

XML/HTML CodeCopy content to clipboard
  1. <link rel="stylesheet" href="css/style.css">
  2. <script src="js/ script.js">script>

doctype, html, head, and body tags are not needed. HTML import immediately loads the document being imported, parses the resources in the document, and executes scripts if any.
Execution order

The way browsers parse HTML documents is linear, which means that the scripts at the top of the HTML will be executed before the bottom. Moreover, browsers usually wait until the JavaScript code is executed before parsing the subsequent code.

In order to prevent script from hindering the rendering of HTML, you can add async or defer attributes to the tag (or you can also put the script tag at the bottom of the page). The defer attribute delays script execution until all pages have been parsed. The async attribute allows the browser to execute scripts asynchronously so that it does not hinder the rendering of HTML. So, how does HTML import work?

The script in the HTML import file is the same as containing the defer attribute. For example, in the following example, index.html will execute script1.js and script2.js first, and then script3.js.

index.html

XML/HTML CodeCopy content to clipboard
  1. <link rel="import" href="component.html"> // 1.   
  2. <title>Import Exampletitle>  
  3. <script src="script3.js">script>        // 4.  

component.html
 

XML/HTML Code复制内容到剪贴板
  1. <script src="js/script1.js">script>     // 2.   
  2. <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复制内容到剪贴板
  1. var link = document.querySelector('link[rel ="import"]');
  2. link.addEventListener('load', function(e) {
  3. var importedDoc = link.import;
  4. // importedDoc points to the document under component.html
  5. });

To get the document object in component.html, use document.currentScript.ownerDocument.

component.html

XML/HTML CodeCopy content to clipboard
  1. var mainDoc = document.currentScript.ownerDocument;
  2. // mainDoc points to the document under component.html

If you are using webcomponents.js, then use document._currentScript instead of document.currentScript. Underscores are used to populate the currentScript attribute because not all browsers support this attribute.

component.html


XML/HTML CodeCopy content to clipboard
  1. var mainDoc = document._currentScript.ownerDocument;
  2. // mainDoc points to the document under component.html

By adding the following code at the beginning of the script, you can easily access the document object in component.html regardless of whether the browser supports HTML import.

document._currentScript = document._currentScript || document.currentScript;
Performance considerations

One benefit of using HTML import is to organize resources, but it also means that when loading these resources, the header becomes too large due to the use of some additional HTML files. There are a few points to consider:
Resolving dependencies

What happens if the main HTML file depends on multiple import files, and the import files contain the same library? For example, if you want to load jQuery from an import file, if each import file contains a script tag that loads jQuery, then jQuery will be loaded twice and executed twice.

index.html

XML/HTML CodeCopy content to clipboard
  1. <link rel="import" href="component1.html">
  2. <link rel="import" href="component2.html">

component1.html

XML/HTML CodeCopy content to clipboard
  1. <script src="js/jquery.js ">script> 

component2.html

HTML import automatically solves this problem for you.

Different from loading script tags twice, HTML import no longer loads and executes the already loaded HTML file. Taking the previous code as an example, by packaging the script tag that loads jQuery into an HTML import file, jQuery is only loaded and executed once.

But there’s a problem: we’ve added a file to load. How to deal with the expanding number of files? Fortunately, we have a tool called vulcanize to solve this problem.
Merge network requests

Vulcanize can merge multiple HTML files into one file, thereby reducing the number of network connections. You can install it with npm and use it from the command line. You may also be using grunt and gulp to host some tasks, in which case you can vulcanize as part of the build process.

In order to resolve dependencies and merge the import files in index.html, use the following command:


Copy code
The code is as follows:
$ vulcanize -o vulcanized.html index.html

By executing this command, the dependencies in index.html will be parsed and a merged HTML file called vulcanized.html will be generated. To learn more about vulcanize, see here.

Note: The server push feature of http2 is being considered for future elimination of file linking and merging.
Combine Template, Shadow DOM, custom elements and HTML import

Let’s use HTML import for the code for this article series. You may not have seen these articles before, so let me explain them first: Template allows you to define the content of your custom elements declaratively. Shadow DOM allows an element's style, ID, and class to only apply to itself. Custom elements allow you to customize HTML tags. By combining these with HTML imports, your custom web components become modular and reusable. Anyone can use it by adding a Link tag.

x-component.html


XML/HTML CodeCopy content to clipboard
  1. <template id="template">  
  2.   <style>  
  3.     ...   
  4.   style>  
  5.   <div id="container">  
  6.     <img src="http://webcomponents.org/img/logo.svg">  
  7.     <content select="h1">content>  
  8.   div>  
  9. template>  
  10. <script>  
  11.   // This element will be registered to index.html   
  12.   // Because `document` here means the one in index.html   
  13.   var XComponent = document.registerElement('x-component', {   
  14.     prototype: Object.create(HTMLElement.prototype, {   
  15.       createdCallback: {   
  16.         value: function() {   
  17.           var root = this.createShadowRoot();   
  18.           var template = document.querySelector('#template');   
  19.           var clone = document.importNode(template.content, true);   
  20.           root.appendChild(clone);   
  21.         }   
  22.       }   
  23.     })   
  24.   });   
  25. script>  

index.html
 

XML/HTML Code复制内容到剪贴板
  1. ...
  2. <link rel="import" href="x-component.html">
  3. head>
  4. <body>
  5. <x-component>
  6.  <h1>This is Custom Elementh1>
  7. x-component>
  8. ...

Note that because the document object in x-component.html is the same as index.html, you don’t need to write any tricky code, it will be automatically registered for you.
Supported browsers

Chrome and Opera provide support for HTML import, and Firefox will not support it until December 2014 (Mozilla stated that Firefox does not plan to provide support for HTML import in the near future, claiming that it needs to first understand how ES6 modules are implemented) .

You can go to chromestatus.com or caniuse.com to check whether the browser supports HTML import. If you want to use HTML import on other browsers, you can use webcomponents.js (formerly platform.js).
Related Resources

That’s all for HTML import. If you want to learn more about HTML import, please go to:

HTML Imports: #include for the web – HTML5Rocks
HTML Imports spec

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn