内嵌css_如何以及为什么应该内嵌关键CSS

内嵌css

A website stage setting

In the early days of the internet, websites were primarily used to show text based information. Slowly, our connection speeds have improved and users have been able to download high-resolution images and videos fairly quickly. Now websites do a lot more than just provide necessary information in the form of text. Websites are becoming more complicated, with CSS and JavaScript frameworks, plugins galore and more. With all of this in play, loading all the necessary files for all of this can take some time.

在互联网的早期,网站主要用于显示基于文本的信息。 慢慢地,我们的连接速度有所提高,用户已经能够相当快地下载高分辨率的图像和视频。 现在,网站不仅仅提供文本形式的必要信息,还可以做很多事情。 网站越来越复杂,有CSS和JavaScript框架,丰富的插件等等。 在进行所有这些操作的同时,加载所有必要文件需要花费一些时间。

A faster website can result in a better user experience, which can make a huge difference in a website’s success. What can developers do to start making performance improvements? One thing that developers can do which helps greatly is to inline critical CSS and load non-critical CSS asynchronously. In this article, we’ll cover these points one-by-one and help you improve your website’s performance.

更快的网站可以带来更好的用户体验,这可以对网站的成功产生巨大的影响。 开发人员可以做什么来开始提高性能? 开发人员可以做的一件非常有用的事情是内联关键CSS并异步加载非关键CSS。 在本文中,我们将逐一介绍这些要点,并帮助您提高网站的性能。

什么是关键CSS? (What is Critical CSS?)

The critical CSS in your project is the CSS that’s used to style the above-the-fold content of your website. Above-the-fold content is what users see on your website first, which can include navigation and other elements. So it’s very important to properly style and render this part of the website as quickly as possible.

项目中的关键CSS是用于样式化网站上方内容CSS。 折叠式内容是用户首先在您的网站上看到的内容,其中可以包括导航和其他元素。 因此,尽快对网站的这一部分进行适当的样式设置和呈现非常重要。

One thing that I would like to mention here is that your visitors probably use a myriad of devices with different viewports to visit your website. So, above-the-fold content is not going to be of much help by itself. To solve this issue, you should also consider any CSS related to the basic layout and typography to be critical as well.

我想在这里提及的一件事是,您的访问者可能会使用多种具有不同视口的设备来访问您的网站。 因此,折叠式内容本身不会有太大帮助。 要解决此问题,您还应该考虑与基本布局和版式相关的所有CSS也是至关重要的。

Modern web development practices often recommend that you inline your critical CSS. It would be placed into your web page like so:

现代Web开发实践通常建议您内联关键CSS。 它将像这样放置在您的网页中:

<!doctype html>
<html>
  <head>
    <title>An Optimized Web Page</title>
    <style type="text/css"> (Your minified critical CSS would be here) </style>
  </head>
  <body>
     (Your markup)
  </body>
</html>

为什么需要内联? (Why is Inlining Necessary?)

If you head over to Google PageSpeed Insights and analyze one of your web pages, you might see warnings about optimizing your CSS delivery by inlining critical CSS and loading render-blocking stylesheets asynchronously.

如果您访问Google PageSpeed Insights并分析您的网页之一,则可能会看到有关通过内联关键CSS并异步加载渲染阻止样式表来优化CSS交付的警告。

Browsers won’t render the above-the-fold content of your web pages unless they have loaded all of your CSS files. This can be a big deal when a lot of files need to be loaded.

除非浏览器已经加载了所有CSS文件,否则它们不会呈现网页的首屏内容。 当需要加载许多文件时,这可能是一件大事。

Not all of your users will have a fast internet connection and waiting for the libraries, CSS and JavaScript to load before they can actually access the content they came for can be very frustrating. Even users with fast internet can lose connectivity in certain situations, like when they are passing through a tunnel. At this point, they would still be able to access the main content if your website has inlined critical CSS and doesn’t load other files before showing main content.

并非您的所有用户都将拥有快速的Internet连接,并且在库,CSS和JavaScript加载之前才可以访问他们真正想要的内容,这会非常令人沮丧。 即使是具有快速Internet连接的用户,在某些情况下(例如通过隧道时)也可能会失去连接。 此时,如果您的网站已内嵌关键CSS且在显示主要内容之前未加载其他文件,则他们仍然可以访问主要内容。

The image below illustrates the difference between a regular and an optimized web page. As you can see, the optimized version will allow users to access the content about 0.5 seconds earlier. The improvements will be more pronounced when there are a lot of extra libraries that need to be loaded.

下图说明了常规网页和优化网页之间的区别。 如您所见,优化版本将允许用户在0.5秒之前访问内容。 当有很多额外的库需要加载时,这些改进将更加明显。

Inline CSS loading stages

您是否应该内嵌关键CSS? (Should You Inline Critical CSS?)

It depends on the situation. If you are not using any heavy frameworks or libraries and your own CSS files also have a small size, then you may not need to inline your CSS.

这取决于实际情况。 如果您不使用任何繁重的框架或库,并且您自己CSS文件也很小,那么您可能不需要内联CSS。

If you are using a framework like Bootstrap, you are probably not using all the features that the framework offers. In that case, you can just extract the critical CSS from the framework’s stylesheets and load the actual framework asynchronously. This should significantly improve your website’s speed.

如果使用的是Bootstrap之类的框架,则可能未使用该框架提供的所有功能。 在这种情况下,您可以从框架的样式表中提取关键CSS并异步加载实际的框架。 这将大大提高您网站的速度。

While inlining, stylesheets can be cached. HTML often is not cached (it is often not a good idea to do so!). This means there can occasionally be a difference between the two. Keep this in mind when making updates! Also, the inlined CSS will result in some extra page weight every time a user loads your website. For example, if there is 30kB of inline CSS on every page of your website then 10 page views by a single user will cost the user 300kB. It may not sound like a big deal but data is expensive in some parts of the world (and on some 3G/4G data plans). Ensure that the CSS you are planning to inline is genuinely critical to your web page and you are not inlining everything.

内联时,可以缓存样式表。 HTML通常不会被缓存(这样做通常不是一个好主意!)。 这意味着两者之间有时可能会有所不同。 进行更新时请记住这一点! 另外,每次用户加载您的网站时,内联CSS都会增加页面的重量。 例如,如果您网站的每个页面上都有30kB的内联CSS,则单个用户的10次页面浏览将使该用户花费300kB。 听起来似乎没什么大不了,但在世界某些地区(以及某些3G / 4G数据计划中),数据价格昂贵。 确保您计划内联CSS对您的网页确实至关重要,并且您没有内联所有内容

寻找关键CSS (Finding Critical CSS)

Finding critical CSS manually will be a daunting and boring task. Fortunately, there are tools available that can help you do it quickly.

手动查找关键CSS将是一项艰巨而无聊的任务。 幸运的是,有可用的工具可以帮助您快速完成。

使用咕unt声 (Using Grunt)

If you are familiar with the Grunt build system, there is a plugin which makes this process easier — the popular grunt-critical plugin. If you prefer Gulp or using npm, see the next sections for how to do this process with those.

如果您熟悉Grunt构建系统,则可以使用一个插件使此过程更容易-流行的grunt-critical插件。 如果您更喜欢Gulp或使用npm,请参阅以下各节以了解如何使用它们。

First, you need to install the plugin using the following command:

首先,您需要使用以下命令安装插件:

npm install grunt-critical --save-dev

You also need to create your Gruntfile.js. This will contain all the code to set various options for the plugin including viewport dimensions and the path to source and destination file. Here is an example:

您还需要创建您的Gruntfile.js 。 这将包含用于设置插件各种选项的所有代码,包括视口尺寸以及源文件和目标文件的路径。 这是一个例子:

module.exports = function(grunt) {

  grunt.initConfig({
    critical: {
      extract: {
        options: {
          base: './',
          width: 1024,
          height: 768,
          minify: true
        },
        src: 'path/to/initial.html',
        dest: 'path/to/final.html'
      }
    }
  });

  grunt.loadNpmTasks('grunt-critical');
  grunt.registerTask('default', ['critical']);

};

Inside our wrapper function, we use the grunt.initConfig method to specify all configuration options. In this case, I have specified a base directory in which the source and destination files are to be written. I have also set the minify option to true. This gives me a final minified version of the critical CSS that the plugin extracts. The src property contains the location of our source file which is to be operated against. The dest property contains the location where the final output needs to be saved.

在包装函数中,我们使用grunt.initConfig方法指定所有配置选项。 在这种情况下,我指定了要在其中写入源文件和目标文件的基本目录。 我也将minify选项设置为true 。 这为我提供了该插件提取的关键CSS的最终精简版。 src属性包含要对其进行操作的源文件的位置。 dest属性包含需要保存最终输出的位置。

In case the dest file is a stylesheet, the resulting CSS is saved to a file for use in future. However, if the dest property is a markup file (HTML, PHP and so on), then the CSS is inlined and the existing stylesheets are wrapped in a JavaScript function to load them asynchronously. A noscript block is also added for users who have disabled JavaScript. There are other options available as well. You can access the full list of options on critical’s documentation.

如果dest文件是样式表,则将生成CSS保存到文件中以备将来使用。 但是,如果dest属性是标记文件(HTML,PHP等),则内联CSS并将现有样式表包装在JavaScript函数中以异步加载它们。 还为禁用JavaScript的用户添加了noscript块。 还有其他可用选项。 您可以访问Critical文档中的选项的完整列表。

Now, you can just run the plugin by typing grunt into the console:

现在,您只需在控制台中输入grunt即可运行插件:

C:\path\to\project>grunt

If your initial file had the following markup:

如果您的初始文件具有以下标记:

<!doctype html>
<html>
  <head>
    <title>The Optimizer</title>
    <link rel="stylesheet" href="link/to/stylesheet">
  </head>
  <body>
     <div>All the markup stuff</div>
  </body>
</html>

It will now look like:

现在看起来像:

<!doctype html>
<html>
  <head>
    <title>The Optimizer</title>
    <style type="text/css">Minified Inlined CSS</style>
    <script id="loadcss">
       JavaScript to load styles asynchronously...
    </script>
    <noscript>
      <link rel="stylesheet" href="link/to/stylesheet">
    </noscript>
  </head>
  <body>
     <div>All the markup stuff</div>
  </body>
</html>

As you can see, this plugin does all your work for you. Now, if you analyze your web page using PageSpeed, you should get a better score. In my case, the score changed from 86 to 95.

如您所见,此插件可以为您完成所有工作。 现在,如果您使用PageSpeed分析网页,您的得分将会更高。 以我为例,分数从86变为95。

There are other plugins available for Grunt that achieve a similar feat — grunt-criticalcss and grunt-penthose. However, when using these plugins you will have to specify the stylesheets from which to extract the critical CSS.

Grunt还有其他可实现类似功能的插件-grunt -criticalcssgrunt-penthose 。 但是,使用这些插件时,必须指定从中提取关键CSS的样式表。

使用npm模块 (Using npm Modules)

Critical is the npm package created by Addy Osmani, it contains the functionality that the grunt-critical plugin uses. You can use it without Grunt to extract and inline critical path or above the fold CSS from a web page using JavaScript and npm. To install the package, you need to run:

Critical是Addy Osmani创建的npm软件包,它包含grunt-critical插件使用的功能。 您可以在不使用Grunt的情况下使用它来使用JavaScript和npm从网页中提取并内嵌关键路径或在折叠CSS上方。 要安装该软件包,您需要运行:

npm install critical --save-dev

Once the package has been installed, you need to create a JavaScript file in the project directory and put the following code in it.

安装软件包后,您需要在项目目录中创建一个JavaScript文件,并将以下代码放入其中。

var critical = require('critical');

critical.generate({
  inline: true,
  base: 'initial/',
  src: 'homepage.html',
  dest: 'final/homepage.html',
  width: 1366,
  height: 768
});

You can specify a bunch of options to create your optimized web page. Setting inline to true will generate an HTML page with CSS inlined, otherwise a CSS file will be generated. The width and height option set the dimensions of our target viewport. There are a lot of other options like minifying the inlined CSS which you can find on the critical npm package’s documentation. The markup of the optimized web page will look similar to the output by the grunt plugin.

您可以指定许多选项来创建优化的网页。 将inline设置为true将生成带有内联CSSHTML页面,否则将生成CSS文件。 widthheight选项设置目标视口的尺寸。 还有很多其他选项,例如缩小内联CSS,您可以在关键的npm软件包的文档中找到它们 。 优化网页的标记看起来与grunt插件的输出类似。

Another npm module that is available for you to use is the critical-css module. This module generates the critical CSS from the supplied URL. The generated CSS can be further processed using a callback function because the grunt plugin is based on this package.

您可以使用的另一个npm模块是critical-css模块。 该模块从提供的URL生成关键CSS。 可以使用回调函数进一步处理生成CSS,因为grunt插件基于此软件包。

使用Gulp (Using Gulp)

If you are more comfortable working with Gulp, Addy Osmani recommends Gulp users use the Critical npm module directly. The example he provides on the Critical GitHub page for Gulp users looks like so:

如果您更习惯使用Gulp,Addy Osmani建议Gulp用户直接使用Critical npm模块。 他在Critical GitHub页面上为Gulp用户提供的示例如下所示:

var critical = require('critical').stream;

// Generate & Inline Critical-path CSS
gulp.task('critical', function () {
  return gulp.src('dist/*.html')
    .pipe(critical({base: 'dist/', inline: true, css: ['dist/styles/components.css','dist/styles/main.css']}))
    .pipe(gulp.dest('dist'));
});

The Critical team also have a sample Gulp project showing this in action.

Critical团队还有一个示例Gulp项目 ,说明了这一过程的实际效果。

There is also a gulp-critical-css plugin to generate critical CSS. However, this one works by extracting certain selector types from your CSS, rather than by detecting above-the-fold elements and so on.

还有一个gulp-critical-css插件可以生成关键CSS。 但是,此方法的工作原理是从CSS中提取某些选择器类型,而不是通过检测折叠元素等。

更多资源 (More Resources)

Another tool available is the Critical Path CSS Generator by Jonas Ohlsson. All you have to do is enter your page URL and then supply all the CSS from which you want to extract the critical CSS. Clicking on the “Create Critical Path CSS” button after that will output your CSS.

另一个可用的工具是Jonas Ohlsson的Critical Path CSS Generator 。 您所要做的就是输入页面URL,然后提供要从中提取关键CSS的所有CSS。 单击“创建关键路径CSS”按钮后,将输出您CSS。

The article on CSS-Tricks outlines how you can use CSS preprocessors to author critical fold CSS. Additionally, SitePoint has also published an excellent article about optimizing critical rendering path in the past that you can read to gain a deeper understanding of the topic.

有关CSS-Tricks的文章概述了如何使用CSS预处理器来编写关键折叠CSS 。 此外,SitePoint过去还发表了一篇关于优化关键渲染路径的出色文章,您可以阅读该文章以更深入地了解该主题。

结论 (Conclusion)

Whether you should or shouldn’t inline critical CSS depends on the visiting pattern of your users and the structure of your website. If your website is a one pager and visitors are not going visit it frequently, or if you’ve got a complex site with frameworks and plugins, inlining critical CSS can improve performance significantly.

是否应该内联关键CSS取决于用户的访问模式和网站的结构。 如果您的网站是一个寻呼机,并且访问者不想经常访问它,或者您的网站包含框架和插件,那么内联关键CSS可以显着提高性能。

The only concern about inlining is that it adds additional page weight for each visit. This can be mitigated by using cookies and sending critical CSS only during the first visit while still loading the full CSS file asynchronously and then caching it. It is a little complicated but you get the best of both worlds.

内联的唯一问题是每次访问都会增加页面权重。 通过使用cookie并仅在第一次访问时发送关键CSS即可缓解这种情况,同时仍然异步加载完整CSS文件然后对其进行缓存。 这有点复杂,但是您可以兼得两全。

Have you tried inlining CSS in your own projects? How significant were the improvements? Do you have any advice for fellow developers? Let us know in the comments.

您是否尝试过在自己的项目中内联CSS? 改进有多重要? 您对其他开发人员有什么建议吗? 让我们在评论中知道。

翻译自: https://www.sitepoint.com/how-and-why-you-should-inline-your-critical-css/

内嵌css

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值