Html CSS 交付优化:如何延迟 css 加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19374843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:28:17  来源:igfitidea点击:

CSS delivery optimization: How to defer css loading?

javascripthtmlcssgoogle-pagespeeddeferred-loading

提问by RafaSashi

I am trying to optimize the CSS deliveryfollowing the google documentation for developers https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example

我正在尝试按照开发人员的谷歌文档优化 CSS 交付https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example

As you can see in the example of inlining a small CSS file the critical CSS in inlined in the head and the original small.css is loaded after onload of the page.

正如您在内联小 CSS 文件的示例中所见,关键 CSS 内联在头部,原始 small.css 在页面加载后加载

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

My question regarding this example:

我关于这个例子的问题:

How to load a large css file after onload of the page?

如何在页面加载后加载一个大的 css 文件?

采纳答案by Fred

If you don't mind using jQuery, here is a simple code snippet to help you out. (Otherwise comment and I'll write a pure-js example

如果您不介意使用 jQuery,这里有一个简单的代码片段可以帮助您。(否则评论,我会写一个纯js的例子

function loadStyleSheet(src) {
    if (document.createStyleSheet){
        document.createStyleSheet(src);
    }
    else {
        $("head").append($("<link rel='stylesheet' href='"+src+" />"));
    }
};

Just call this in your $(document).ready()or window.onloadfunction and you're good to go.

只需在您的$(document).ready()orwindow.onload函数中调用它,您就可以开始了。

For #2, why don't you try it out? Disable Javascript in your browser and see!

对于#2,你为什么不试试呢?在您的浏览器中禁用 Javascript 并查看!

By the way, it's amazing how far a simple google search can get you; for the query "post load css", this was the fourth hit... http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery

顺便说一句,一个简单的谷歌搜索可以让你走多远真是太神奇了;对于查询"post load css",这是第四次命中... http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery

回答by Salvi Pascual

A little modification to the function provided by Fred to make it more efficient and free of jQuery. I am using this function in production for my websites

对 Fred 提供的函数稍作修改,使其更高效且无需 jQuery。我在我的网站的生产中使用此功能

        // to defer the loading of stylesheets
        // just add it right before the </body> tag
        // and before any javaScript file inclusion (for performance)  
        function loadStyleSheet(src){
            if (document.createStyleSheet) document.createStyleSheet(src);
            else {
                var stylesheet = document.createElement('link');
                stylesheet.href = src;
                stylesheet.rel = 'stylesheet';
                stylesheet.type = 'text/css';
                document.getElementsByTagName('head')[0].appendChild(stylesheet);
            }
        }

回答by RafaSashi

In addition to Fred's answer:

除了弗雷德的回答:

Solution using jQuery & Noscript

使用 jQuery & Noscript 的解决方案

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    <script type="text/javascript" src="../jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
        if($("body").size()>0){
                if (document.createStyleSheet){
                    document.createStyleSheet('style.css');
                }
                else {
                    $("head").append($("<link rel='stylesheet' 
                    href='style.css' 
                    type='text/css' media='screen' />"));
                }
            }
        });
    </script>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

from http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery

来自http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery

Using pure Javascript & Noscript

使用纯 Javascript 和 Noscript

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    <script type="text/javascript">
          var stylesheet = document.createElement('link');
          stylesheet.href = 'style.css';
          stylesheet.rel = 'stylesheet';
          stylesheet.type = 'text/css';
          document.getElementsByTagName('head')[0].appendChild(stylesheet);
    </script>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

回答by Raja Khoury

Try this snippet

试试这个片段

The authorclaims it was published by Google's PageSpeed Team

作者声称,它是由谷歌的团队的PageSpeed公布

<script>
    var cb = function() {
    var l = document.createElement('link'); l.rel = 'stylesheet';
    l.href = 'yourCSSfile.css';
    var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h); };
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
              webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) raf(cb);
    else window.addEventListener('load', cb);
</script>

回答by Accountant ?

WARNING: body{background-image: url("http://example.com/image.jpg");}in css files will make your css files still render-blocking.

警告:body{background-image: url("http://example.com/image.jpg");}在 css 文件中会使你的 css 文件仍然阻塞渲染。

If you tried all the solutions above and you still get the render-blocking warning from PageSpeed insights then you probably have this style rule in your css files. After hours of tests it turns out that this rule is what making ALLof my css to be flagged as render-blocking resources at PageSpeed insights. I found the same issue has been discussed before.

如果您尝试了上述所有解决方案,但仍然收到来自 PageSpeed Insights 的渲染阻止警告,那么您的 css 文件中可能包含此样式规则。经过数小时的测试,结果证明是这条规则使我的所有css 都在 PageSpeed 洞察中被标记为阻止渲染的资源。我发现之前已经讨论过同样的问题。

I don't know why body{background-image: url(...)do this for all the css files!, although I have different images resources in the file for the buttons, icons, ...etc .

我不知道为什么body{background-image: url(...)对所有 css 文件都这样做!,尽管我在文件中为按钮、图标等提供了不同的图像资源。

I fixed this by moving this rule from the .cssfile and put it in the inline styles. Unfortunately, you will have to break your css plan and put the rule in all of your layouts HTML files instead of being in 1 css file that is imported in all of your HTML layouts, but the 90s and green color in PageSpeed insights deserve it.

我通过从.css文件中移动此规则并将其放入内联样式来解决此问题。不幸的是,您将不得不打破 css 计划并将规则放在所有布局 HTML 文件中,而不是在所有 HTML 布局中导入的 1 个 css 文件中,但 PageSpeed 见解中的 90 年代和绿色值得它。

回答by MrJaid

Fixed mine by introducing placing all css files at the bottom of the page, after the body tag. but this introduces a new problem, the page loads un-styled html for noticeable mili seconds before applying the style. For this I fixed by introducing a splash screen all styled on the page.

通过引入将所有 css 文件放置在页面底部的 body 标记之后来修复我的问题。但这引入了一个新问题,页面在应用样式之前加载未设置样式的 html 数毫秒。为此,我通过在页面上引入所有样式的闪屏来解决这个问题。