如何异步加载 CSS

新手上路,请多包涵

我正在尝试消除 2 个在我的网站上呈现阻塞的 CSS 文件 - 它们出现在 Google Page Speed Insights 上。我遵循了不同的方法,但都没有成功。但是,最近,我发现了一篇关于 Thinking Async 的帖子,当我应用此代码时: <script async src="https://third-party.com/resource.js"></script> 它确实消除了问题。

但是,发布后,页面失去了样式。我不太确定发生了什么,因为代码有效,但上传后的样式不起作用。感谢您对此的帮助。谢谢

原文由 Paulina994 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 787
1 个回答

2020年更新


简单的答案(完整的浏览器支持):

 <link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

记录的答案(带有可选的预加载和禁用脚本的回退):

  <!-- Optional, if we want the stylesheet to get preloaded. Note that this line causes stylesheet to get downloaded, but not applied to the page. Use strategically — while preloading will push this resource up the priority list, it may cause more important resources to be pushed down the priority list. This may not be the desired effect for non-critical CSS, depending on other resources your app needs. -->
 <link rel="preload" href="style.css" as="style">

 <!-- Media type (print) doesn't match the current environment, so browser decides it's not that important and loads the stylesheet asynchronously (without delaying page rendering). On load, we change media type so that the stylesheet gets applied to screens. -->
 <link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

 <!-- Fallback that only gets inserted when JavaScript is disabled, in which case we can't load CSS asynchronously. -->
 <noscript><link rel="stylesheet" href="style.css"></noscript>

预加载和异步组合:

如果您需要预加载和异步 CSS,此解决方案只需结合上面记录的答案中的两行,使其稍微更简洁。同样,正如上面记录的答案中详述的那样,预加载实际上可能并没有好处。

 <link href="style.css" rel="preload" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="style.css"></noscript>

其他注意事项:

请注意,一般来说,如果您要异步加载 CSS,通常建议您内联 关键 CSS ,因为 CSS 是一种渲染阻塞资源 是有原因的

感谢 filament group 的许多异步 CSS 解决方案。

此方法可能不适用于启用的内容安全策略。

原文由 jabacchetta 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题