使用 2018 年全新的 "HTML import" 草案快速加载网页:将 rel="stylesheet" 替换为 rel="import"

Fast webpage loading using the all new "HTML import" draft in 2018: replacing rel="stylesheet" with rel="import"

在使用 google 页面速度分析器测试我的移动友好页面时,它说:

Eliminate render-blocking JavaScript and CSS in above-the-fold content. Your page has 2 blocking CSS resources. This causes a delay in rendering your page. None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

据此 google page and w3c 2018 March draft 网络很快将支持 HTML 导入。:

Note that the web platform will soon support loading stylesheets in a non-render-blocking manner, without having to resort to using JavaScript, using HTML Imports.

我的第一个问题是:

将旧样式样式表转换为HTML导入的方法有哪些?

我可以简单地改变...

<link rel="stylesheet" type="text/css" href="all.css"/>
<link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=etc'/>

...进入:

<link rel="import" type="text/css" href="all.css"/>
<link rel='import' type='text/css' href='https://fonts.googleapis.com/css?family=etc'/>

我的第二个问题是:

(何时)Web 平台[主要浏览器,如 Chrome、Edge、Firefox 和主要服务器技术,如 php apachee 上的 7.2] 是否准备好从 rel="stylesheets"rel="import"?

我的第三个奖励问题是:

除了根据 google 的小幅性能提升外,(将来)使用 HTML import 与旧的 rel="stylesheet" 相比是否会出现任何故障站点?

First question

暂时没有办法。 HTML 导入是一种在其他 HTML 文档中包含和重用 HTML 文档的方法,请参阅 HTML Imports 文档。

Second question

很难说 rel="import" 何时会广泛可用,但您可以在 Can I Use 网站 https://caniuse.com/#search=import 上轻松跟踪浏览器支持情况,它也显示下一个要发布的版本是否支持它。

Third bonus question

rel="import"是导入HTML个文件。

rel="stylesheets"是导入CSS个文件。

您仍然需要使用 rel="stylesheets" 来加载您的 CSS 文件。

您不能简单地将 stylesheet <link> 转换为 import <link>,因为 <link rel="import"> 只会加载 HTML 文档,而不是 CSS 样式表。

<link rel="import" href="imported-styles.html" async>

因此,通过HTML导入的样式必须包含在元素中:

进口-styles.html:

<style> 
    //content of all.css
    ... 
</style>

或者使用标准 <link rel="stylesheet">:

进口-styles.html:

<link rel="stylesheet" type="text/css" href="all.css"/>
<link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=etc'/>

请注意,如果您不想在处理主 HTML 文档的其余部分之前等待导入的文档加载完毕,则应使用 async 属性。


现在 only Chrome and Opera 正在本地实施 HTML 导入。其他浏览器供应商不打算实施它,因此您需要在 Edge 和 Firefox 中使用 polyfill。

这是一项前端技术,因此服务器框架并不真正关心。

使用 HTML 导入的缺点是,在某些特殊情况下,使用 polyfill 实现的行为可能会略有不同(大多数 polyfill 都是如此)。请参阅 polyfill 的 limitatons

HTML 导入实际上已被弃用,尽管它已在 Chrome 中实现。所以不要用它。

https://dev.to/nektro/the-downfall-of-html-imports-is-upon-us-to-me

一个类似的功能叫做 "HTML Module" 将在未来推出,但甚至标准本身仍在 Github 上讨论,所以我们需要很长时间能够使用它。

https://github.com/dglazkov/webcomponents/blob/html-modules/proposals/HTML-Imports-and-ES-Modules.md