A brief introduction to file import in HTML5

Time:2022-1-1

Template, shadow Dom and custom elements make it easier for you to create UI components than before. However, resources such as HTML, CSS and JavaScript still need to be loaded one by one, which is very inefficient.

Removing duplicate dependencies is not easy. For example, now loading the jQuery UI or bootstrap requires adding separate tags for JavaScript, CSS, and web fonts. If your web component applies multiple dependencies, things become more complex.

HTML import lets you load these resources as a merged HTML file.
Using HTML import

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

index.html
 

XML/HTML CodeCopy contents to clipboard
  1. <link rel=“import” href=“component.html” >    

You can import files into HTML Adding any resources, including scripts, style sheets, and fonts, is just like adding resources to normal HTML.

component.html
 

XML/HTML CodeCopy contents 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 required. HTML import will immediately load the document to be imported, parse the resources in the document, and execute them immediately if there are scripts.
Execution sequence

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

To prevent script from interfering with HTML rendering, you can add async or defer attributes to the tag (or you can put the script tag at the bottom of the page). The defer attribute delays the execution of the script until all pages are parsed. The async attribute allows the browser to execute scripts asynchronously without interfering with HTML rendering. 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 first execute script1 JS and script2 JS, and then execute script3 js。

index.html
 

XML/HTML CodeCopy contents to clipboard
  1. <link rel=“import” href=“component.html”> // 1.   
  2. <title>Import Example</title>  
  3. <script src=“script3.js”></script>        // 4.  

component.html
 

XML/HTML CodeCopy contents to clipboard
  1. <script src=“js/script1.js”></script>     // 2.   
  2. <script src=“js/script2.js”></script>     // 3.  

1. In index Load component.html HTML and wait for execution

2. Execute component Script1 in HTML js

3. After executing script1 JS and execute component Script2 in HTML js

4. After executing script2 JS then executes index Script3 in HTML js

Note that if you add the async attribute to link [rel = “import”], the HTML import will treat it as a script containing the async attribute. It does not wait for the HTML import file to execute and load, which means that the HTML import does not hinder the rendering of the HTML main file. This also makes it possible to improve the performance of the website, unless there are other scripts that rely on the execution of HTML import files.
Cross domain import

Fundamentally speaking, HTML import cannot import resources from other domain names.

For example, you can’t start from http://webcomponents.org/ To http://example.com/ Import HTML file. Cross domain sharing (CORS can be used to bypass this restriction). To learn about CORS, please read this article.
Window and document objects in HTML import files

I mentioned earlier that the script will be executed when importing the HTML file, but this does not mean that the tags in the HTML import file will also be rendered by the browser. You need to write some JavaScript code to help.

When using JavaScript in an HTML import file, one thing to beware of is that the document object in the HTML import file actually refers to the document object in the HTML main file. Take the previous code as an example, index HTML and} component HTML documents refer to index HTML document object. How can I use HTML to import a document in a file? Use the import attribute in link.

index.html
 

XML/HTML CodeCopy contents to clipboard
  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 component For the document object in HTML, use document currentScript. ownerDocument.

component.html
 

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

If you’re 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 contents 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 component The document object in HTML, regardless of whether the browser supports HTML import.

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

One advantage of using HTML import is that it can 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 several points to consider:
Resolve dependency

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

index.html
 

XML/HTML CodeCopy contents to clipboard
  1. <link rel=“import” href=“component1.html”>  
  2. <link rel=“import” href=“component2.html”>  

component1.html
 

XML/HTML CodeCopy contents to clipboard
  1. <script src=“js/jquery.js”></script>  

component2.html
 
HTML import automatically helps you solve this problem.

Unlike the method of loading script tags twice, HTML import does not load and execute the loaded HTML files. Taking the previous code as an example, by packaging the script tag loaded with jQuery into an HTML import file, jQuery can only be loaded and executed once.

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

Vulcanize can combine multiple HTML files into one file, thus reducing the number of network connections. You can install it with NPM and use it from the command line. You may also be hosting some tasks with grunt and gulp, so you can use vulcanize as part of the build process.

To resolve dependencies and merge index HTML, use the following command:

Copy code

The code is as follows:

$ vulcanize -o vulcanized.html index.html

By executing this command, index The dependencies in HTML are resolved and a merged HTML file called vulcanized. Html is generated html。 To learn more about vulcanize, please see here.

Note: the server push function of http2 is considered to eliminate file linking and merging in the future.
Combine template, shadow Dom and custom elements with HTML import

Let’s use HTML import for the code in this article series. You may not have read these articles before. Let me explain first: template allows you to define the content of your custom elements in a declarative way. Shadow DOM can make the style, ID and class of an element only work on itself. Custom elements allow you to customize HTML tags. By combining these with HTML import, your custom web components will become modular and reusable. Anyone who adds a link tag can use it.

x-component.html

 

XML/HTML CodeCopy contents 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 CodeCopy contents to clipboard
  1. …   
  2.   <link rel=“import” href=“x-component.html”>  
  3. </head>  
  4. <body>  
  5.   <x-component>  
  6.     <h1>This is Custom Element</h1>  
  7.   </x-component>  
  8.   …  

Note that because x-component The document object in HTML follows index Like HTML, you don’t have to write some tricky code. It will automatically register for you.
Supported browsers

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

You can go to chromestatus Com or caniuse Com query 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 about html import. If you want to learn more about html import, please go to:

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