Home  >  Article  >  Web Front-end  >  A brief introduction to file import in HTML5

A brief introduction to file import in HTML5

不言
不言Original
2018-05-08 15:39:402354browse

This article mainly introduces a brief introduction to file import in HTML, including loading jQuery, execution sequence after import and other knowledge points. Friends in need can refer to

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

Deleting 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.
Using HTML import

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

index.html

##XML/HTML CodeCopy content to clipboard Board

<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 master file" . For example, index.html is the main HTML file, and 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 Code

Copy content to clipboard

<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
doctype, html, The 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 Code

Copy content to clipboard

<link rel="import" href="component.html"> // 1.   
<title>Import Example</title>
<script src="script3.js"></script>        // 4.

component.html


XML/HTML Code

Copy content to clipboard

<script src="js/script1.js"></script>     // 2.   
<script src="js/script2.js"></script>     // 3.
1. Load component.html in index.html and wait for execution

2. Execute script1.js in component.html

3. After executing script1.js, execute script2 in component.html .js

4. After executing script2.js, execute script3.js in index.html

Note that if you add the async attribute to link[rel="import"], the HTML import will Treat it like a script with 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 main HTML file. This also makes it possible to improve website performance, unless there are other scripts that rely on the execution of the HTML import file.

Cross-domain import


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

For example, you cannot import HTML files from http://webcomponents.org/ to http://example.com/. To bypass this limitation, CORS (Cross-Origin Resource Sharing) can be used. To learn about CORS, please read this article.

Window and document objects in HTML import files


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

One thing to be wary of when using JavaScript in an HTML import file is that the document object in the HTML import file actually refers to the document object in the main HTML file. Taking the previous code as an example, the documents of index.html and component.html both refer to the document object of index.html. How can I use HTML to import the document in the file? Use the import attribute in link.

index.html


XML/HTML Code

Copy content to clipboard

var link = document.querySelector(&#39;link[rel="import"]&#39;);   
link.addEventListener(&#39;load&#39;, function(e) {   
  var importedDoc = link.import;   
  // importedDoc points to the document under component.html   
});
In order to get the component. For the document object in html, use document.currentScript.ownerDocument.

component.html


XML/HTML Code

to copy the content to the clipboard

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导入。
document._currentScript = document._currentScript || document.currentScript;
性能方面的考虑

使用HTML 导入的一个好处是能够将资源组织起来,但是也意味着在加载这些资源的时候,由于使用了一些额外的HTML文件而让头部变得过大。有几点是需要考虑的:
解析依赖

假如HTML主文件要依赖多个导入文件,而且导入文件中含有相同的库,这时会怎样呢?例如,你要从导入文件中加载jQuery,如果每个导入文件都含有加载jQuery的script标签,那么jQuery就会被加载两次,并且也会被执行两次。

index.html

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

<link rel="import" href="component1.html">
<link rel="import" href="component2.html">

component1.html

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

<script src="js/jquery.js"></script>

component2.html
 
HTML导入自动帮你解决了这个问题。

与加载两次script标签的做法不同,HTML 导入对已经加载过的HTML文件不再进行加载和执行。以前面的代码为例,通过将加载jQuery的script标签打包成一个HTML导入文件,这样jQuery就只被加载和执行一次了。

但这还有一个问题:我们增加了一个要加载的文件。怎么处理数目膨胀的文件呢?幸运的是,我们有一个叫vulcanize的工具来解决这个问题。
合并网络请求

Vulcanize 能将多个HTML文件合并成一个文件,从而减少了网络连接数。你可以借助npm安装它,并且用命令行来使用它。你可能也在用 grunt和gulp 托管一些任务,这样的话你可以把vulcanize作为构建过程的一部分。

为了解析依赖以及合并index.html中的导入文件,使用如下命令:

复制代码

代码如下:

$ vulcanize -o vulcanized.html index.html

通过执行这个命令,index.html中的依赖会被解析,并且会产生一个合并的HTML文件,称作 vulcanized.html。学习更多有关vulcanize的知识,请看这儿。

注意:http2的服务器推送功能被考虑用于以后消除文件的连结与合并。
把Template、Shadow DOM、自定义元素跟HTML导入结合起来

让我们对这个文章系列的代码使用HTML导入。你之前可能没有看过这些文章,我先解释一下:Template可以让你用声明的方式定义你的自定义元素的内容。Shadow DOM可以让一个元素的style、ID、class只作用到其本身。自定义元素可以让你自定义HTML标签。通过把这些跟HTML导入结合起来,你自定义的web 组件会变得模块化,具有复用性。任何人添加一个Link标签就可以使用它。

x-component.html

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

<template id="template">
  <style>
    ...   
  </style>
  <p id="container">
    <img src="http://webcomponents.org/img/logo.svg">
    <content select="h1"></content>
  </p>
</template>
<script>
  // This element will be registered to index.html   
  // Because `document` here means the one in index.html   
  var XComponent = document.registerElement(&#39;x-component&#39;, {   
    prototype: Object.create(HTMLElement.prototype, {   
      createdCallback: {   
        value: function() {   
          var root = this.createShadowRoot();   
          var template = document.querySelector(&#39;#template&#39;);   
          var clone = document.importNode(template.content, true);   
          root.appendChild(clone);   
        }   
      }   
    })   
  });   
</script>

index.html

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

...   
  <link rel="import" href="x-component.html">
</head>
<body>
  <x-component>
    <h1>This is Custom Element</h1>
  </x-component>
  ...

注意,因为x-component.html 中的document 对象跟index.html的一样,你没必要再写一些棘手的代码,它会自动为你注册。
支持的浏览器

Chrome 和 Opera提供对HTML导入的支持,Firefox要在2014年12月后才支持(Mozilla表示Firefox不计划在近期提供对HTML导入的支持,声称需要首先了解ES6的模块是怎样实现的)。

你可以去chromestatus.com或caniuse.com查询浏览器是否支持HTML导入。想要在其他浏览器上使用HTML导入,可以用webcomponents.js(原名platform.js)。

相关推荐:

HTML5中form表单标签用法详解

The above is the detailed content of A brief introduction to file import in HTML5. For more information, please follow other related articles on the PHP Chinese website!

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