简体   繁体   English

如何预加载样式表

[英]How to pre-load a stylesheet

I have about 10 style pages throughout my website, some for different pages.我的整个网站大约有 10 个样式页面,其中一些用于不同的页面。 However, I can't just load all of them at the beginning because some styles override other styles.但是,我不能一开始就加载所有这些样式,因为某些样式会覆盖其他样式。 However, I'd like to all load them after a user first hits the site so that there won't be delays (due to loading the static css/js files) when they go to other pages on the site.但是,我想在用户第一次访问网站后全部加载它们,这样当他们转到网站上的其他页面时就不会出现延迟(由于加载静态 css/js 文件)。 Here's basically what I'd like to do:这基本上是我想要做的:

# main page
<link rel="stylesheet" href="http://examplestyle.css">

# load via javascript after 2 second delay -- DO NOT display on the current page
<img src="http://otherstylesheet.css" width="0">

I'm just making something up with loading the css as an image, but basically I'd just like to pre-fetch the http calls after the user hits the landing page.我只是想将 css 作为图像加载,但基本上我只想在用户点击登录页面后预取 http 调用。

This is in the MDN Web Docs:这是在 MDN Web 文档中:

<head>
  <meta charset="utf-8">
  <title>JS and CSS preload example</title>

  <link rel="preload" href="style.css" as="style">
  <link rel="preload" href="main.js" as="script">

  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1>bouncing balls</h1>
  <canvas></canvas>

  <script src="main.js"></script>
</body>

***Not my code, I do not take credit for this code. *** 不是我的代码,我不认为此代码的功劳。

Here's the link to information about CSS preloading: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content这是 CSS 预加载信息的链接: https : //developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

Keep in mind the usability of this feature: https://caniuse.com/#search=preload请记住此功能的可用性: https : //caniuse.com/#search=preload

I have found this -even better- piece of code on https://web.dev/defer-non-critical-css/我在https://web.dev/defer-non-critical-css/上发现了这段甚至更好的代码

<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

I guess you could even use setTimeout() with onload which can be useful in certain situations.我想您甚至可以将setTimeout()onload一起使用,这在某些情况下很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM