CSS交付优化:如何延迟css加载? [英] CSS delivery optimization: How to defer css loading?

查看:290
本文介绍了CSS交付优化:如何延迟css加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按照开发人员的google文档优化CSS传递 https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example



如您在内嵌小型CSS的范例中所看到的以头文件的内联文件格式提供关键CSS,原始small.css在页面加载后加载

 < html> 
< head>
< style>
.blue {color:blue;}
< / style>
< / head>
< body>
< div class =blue>
你好,世界!
< / div>
< / body>
< / html>
< noscript>< link rel =stylesheethref =small.css>< / noscript>

我对此示例的问题:



如何在页面加载后加载大型css文件?

解决方案

如果你不介意使用jQuery,简单的代码片段来帮助你。 (否则注释,我将写一个纯的js示例

  function loadStyleSheet(src){
if .createStyleSheet){
document.createStyleSheet(src);
}
else {
$(head)。append($(< link rel ='stylesheet' href ='+ src +'type ='text / css'media ='screen'/>));
}
};
/ pre>

只需在 $(document).ready()



对于#2,为什么不试试呢?您的浏览器并查看



顺便说一句,令人惊奇的是,一个简单的google搜索可以为您带来多远;对于查询post load css,这是第四个命中...
http://www.vidalquevedo.com/how-to-load-css-stylesheets-dynamically-with-jquery


I am trying to optimize the CSS delivery following the google documentation for developers 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.

<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?

解决方案

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

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

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

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

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

这篇关于CSS交付优化:如何延迟css加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆