“消除首屏内容中阻止渲染的 CSS”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18761251/
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
"Eliminate render-blocking CSS in above-the-fold content"
提问by Niet the Dark Absol
I've been using Google PageSpeed insights to try and improve my site's performance, and so far it's proven extremely successful. Things like deferring scripts worked beautifully, since I already had an in-house version of jQuery's .ready()
to defer scripts until the page had loaded fully, all I had to do was inline that particular function and move the full scripts to the end of the page. That worked great.
我一直在使用 Google PageSpeed 洞察力来尝试提高我网站的性能,到目前为止,它已被证明非常成功。诸如延迟脚本之类的事情工作得很好,因为我已经有一个内部版本的 jQuery.ready()
来延迟脚本直到页面完全加载,我所要做的就是内联该特定函数并将完整脚本移动到页面的末尾。那效果很好。
But now I find myself glaring at the one remaining yellow dot on the checklist: "Eliminate render-blocking CSS in above-the-fold content".
但现在我发现自己盯着清单上剩下的一个黄点:“消除首屏内容中的渲染阻塞 CSS”。
The way my CSS is set up is to have one global _.css
file containing styles that apply to the page structure in general, or are used in more than one or two places across the site. Most pages then have an associated CSS file (for instance, party.php
has party.css
) containing styles specific to that particular page. All CSS files are cached indefinitely, as I append /t=FILEMTIME
to filenames (and later remove them with .htaccess) in order to guarantee that files are updated when they are changed.
我的 CSS 设置方式是让一个全局_.css
文件包含适用于一般页面结构的样式,或者在整个站点的一两个以上位置使用。大多数页面都有一个关联的 CSS 文件(例如,party.php
has party.css
),其中包含特定于该特定页面的样式。所有 CSS 文件都被无限期缓存,因为我附加/t=FILEMTIME
到文件名(然后用 .htaccess 删除它们)以保证文件在更改时更新。
So anyway, Google recommends inlining critical styles needed for above-the-fold content. Trouble is... well, take a look at this screenshot: http://prntscr.com/1qt49e
所以无论如何,谷歌建议内联首屏内容所需的关键样式。问题是......好吧,看看这个截图:http: //prntscr.com/1qt49e
As you can see... ALLof the content is above-the-fold! People hate scrolling, especially on a game that involves loading many pages. So I designed the site to fit on one screen (assuming a good enough resolution). So that means... ALLof the styles apply to above-the-fold content! So... is there any solution? Or am I stuck with that yellow mark on an otherwise near-perfect score?
如您所见......所有内容都在首屏!人们讨厌滚动,尤其是在涉及加载许多页面的游戏中。所以我将网站设计为适合一个屏幕(假设分辨率足够好)。所以这意味着......所有样式都适用于首屏内容!所以……有什么解决办法吗?还是我在其他方面接近完美的分数上被那个黄色标记困住了?
回答by Netsurfer
A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?
之前有人问过一个相关的问题:什么是 Google Pagespeed 中的“首屏内容”?
Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!
首先,您必须注意,这完全是关于“移动页面”。
因此,当我正确解释您的问题和屏幕截图时,这不适合您的网站!
On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.
相反 - 做一些谷歌在他们的指导方针中建议的事情,对于“正常”网站来说,事情会变得更糟。
并不是所有来自谷歌的东西都是“圣杯”,因为它来自谷歌。如果您查看他们的 HTML 标记,他们本身也不是一个好的榜样。
The best advice I could give you is:
我能给你的最好的建议是:
- Set width and height on replaced elements in your CSS, so that the browser can layout the elements and doesn't have to wait for the replaced content!
- 在 CSS 中设置替换元素的宽度和高度,以便浏览器可以布局元素而不必等待替换内容!
Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.
另外,为什么要使用不同的 CSS 文件,而不仅仅是一个?
额外的请求比少量的数据量更糟糕。在第一次请求之后,CSS 文件无论如何都会被缓存。
The things one should always take care of are:
人们应该始终注意的事情是:
- reduce the number of requests as much as possible
- keep your overall page weight as low as possible
- 尽可能减少请求数量
- 保持您的整体页面重量尽可能低
And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)
并且不要对如何获得 100% 的 Google PageSpeed Insights 工具感到困惑......!;-)
Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.
附加 1:这是 Google 向我们展示的页面,他们为Optimize CSS Delivery推荐了什么。
As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web designit is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT(Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!
如前所述,我认为这对“正常”网站来说既不现实也不有意义!因为主要是当您拥有响应式网页设计时,您最肯定会使用媒体查询和其他布局样式。所以如果你不打算首先加载你的 CSS 并且以阻塞的方式你会得到一个FOUT(Flash Of Unstyled Text)。我真的不相信这比至少多几毫秒来呈现页面“更好”!
Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!
Imho Google 正在开始新的“炒作”(当我在 Stackoverflow 上查看有关它的所有问题时)......!
回答by elbowlobstercowstand
How I got a 99/100 on Google Page Speed (for mobile)
我是如何在 Google Page Speed(移动版)上获得 99/100 的
TLDR: Compress and embed your entire css script between your <style></style>
tags.
TLDR:在<style></style>
标签之间压缩和嵌入整个 css 脚本。
I've been chasing down that elusive 100/100 score for about a week now. Like you, the last remaining item was was eliminating "render-blocking css for above the fold content."
大约一个星期以来,我一直在追逐那个难以捉摸的 100/100 分数。像您一样,最后剩下的项目是消除“首屏内容的渲染阻止 css”。
Surely there is an easy solve?? Nope. I tried out Filament group's loadCSSsolution. Too much .js for my liking.
当然有一个简单的解决方案?不。我尝试了Filament group 的 loadCSS解决方案。我喜欢的 .js 太多了。
What about async
attributes for css (like js)? They don't exist.
async
css(如js)的属性怎么样?他们不存在。
I was ready to give up. Then it dawned on me. If linkingthe script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.
我准备放弃了。然后我就明白了。如果链接脚本阻止了渲染,如果我改为将整个 css 嵌入头部会怎样。这样就没有什么可以阻止的了。
It seemed absolutely WRONG to embed 1263 lines of CSS in my style tag. But I gave it a whirl. I compressed it (and prefixed it) first using:
在我的样式标签中嵌入 1263 行 CSS 似乎完全错误。但我试了一下。我首先使用以下方法对其进行了压缩(并为其添加了前缀):
postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/
See the NPM postcss package.
postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/
请参阅 NPM postcss 包。
Now it was just one LONG line of space-less css. I plopped the css in <style>your;great-wall-of-china-long;css;here</style>
tags on my home page. Then I re-analyzed with page speed insights.
现在它只是一长串无空间的 css。我将 css 放入<style>your;great-wall-of-china-long;css;here</style>
主页上的标签中。然后我重新分析了页面速度见解。
I went from 90/100 to 99/100 on mobile!!!
我在手机上从 90/100 变成了 99/100!!!
This goes against everything in me (and probably you). But it SOLVED the problem. I'm just using it on my home page for now and including the compressed css programmatically via a PHP include.
这违背了我(也可能是你)的一切。但它解决了这个问题。我现在只是在我的主页上使用它,并通过 PHP 包含以编程方式包含压缩的 css。
YMMV (your mileage may vary) pending on the length of your css. Google may ding you for too much above the fold content. But don't assume; test!
YMMV(您的里程可能会有所不同)取决于您的 css 长度。谷歌可能会给你太多的首屏内容。但不要假设;测试!
Notes
笔记
I'm only doing this on my home page for now so people get a FAST render on my most important page.
Your css won't get cached.I'm not too worried though. The second they hit another page on my site, the .css willget cached (see Note 1).
我现在只在我的主页上这样做,所以人们可以在我最重要的页面上获得快速渲染。
你的 css 不会被缓存。不过我也不太担心。当他们点击我网站上的另一个页面时,.css将被缓存(见注 1)。
回答by frequent
Few tips that may help:
一些可能有帮助的提示:
I came across this article in CSS optimization yesterday: CSS profiling for ... optimization
A lot of useful info on CSS and what CSS causes the most performance drains.I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.
Also, if you are using a loader like requireJSyou could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO- a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.
我昨天在 CSS 优化中看到了这篇文章: CSS profiling for ... optimization
很多关于 CSS 的有用信息以及哪些 CSS 会导致性能下降。我在 jQueryUK 上看到了以下关于 Googe Chrome (Canary) Dev Tools 中“隐藏的秘密”的演示: DevTools Can do that。查看有关首次绘制时间、重绘和成本高昂的 CSS 的部分。
此外,如果您使用像requireJS这样的加载器,您可以查看其中一个 CSS 加载器插件,称为require-CSS,它使用CSSO- 一个也进行结构优化的优化器,例如。合并具有相同属性的块。我用了几次,它可以在不同情况下节省相当多的 CSS。
Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgoloads for example.
题外话:我第二次 @Enzino 为您正在加载的所有小图标创建一个精灵。文件大小如此之小,以至于无法保证每个图标的服务器往返。还要记住浏览器可以做的并发 http 请求总数。因此,对大量小图标的请求也是“渲染阻塞”。尽管与您的相比是一个空白页面,但我喜欢例如duckduckgo 的加载方式。
回答by Amuk Saxena
Please have a look on the following page https://varvy.com/pagespeed/render-blocking-css.html. This helped me to get rid of "Render Blocking CSS". I used the following code in order to remove "Render Blocking CSS". Now in google page speed insight I am not getting issue related with render blocking css.
请查看以下页面https://varvy.com/pagespeed/render-blocking-css.html。这帮助我摆脱了"Render Blocking CSS"。我使用以下代码来删除“渲染阻塞 CSS”。现在在谷歌页面速度洞察中,我没有遇到与渲染阻塞 css 相关的问题。
<!-- loadCSS -->
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/cssrelpreload.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/loadCSS.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/onloadCSS.js"></script>
<script>
/*!
loadCSS: load a CSS file asynchronously.
*/
function loadCSS(href){
var ss = window.document.createElement('link'),
ref = window.document.getElementsByTagName('head')[0];
ss.rel = 'stylesheet';
ss.href = href;
// temporarily, set media to something non-matching to ensure it'll
// fetch without blocking render
ss.media = 'only x';
ref.parentNode.insertBefore(ss, ref);
setTimeout( function(){
// set media back to `all` so that the stylesheet applies once it loads
ss.media = 'all';
},0);
}
loadCSS('styles.css');
</script>
<noscript>
<!-- Let's not assume anything -->
<link rel="stylesheet" href="styles.css">
</noscript>
回答by Glipt
I too have struggled with this new pagespeed metric.
我也一直在努力解决这个新的页面速度指标。
Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.
虽然我没有找到让我的分数回到 %100 的实用方法,但我发现一些有用的东西。
Combining all css into one file helped a lot. All my sites are back up to %95 - %98.
将所有 css 合并到一个文件中很有帮助。我所有的网站都备份到 %95 - %98。
The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.
我唯一能想到的另一件事是在第一页上内联所有必要的 css(这似乎是大部分 - 至少对于我的页面)以获得甜蜜的高分。尽管它可能有助于您的速度得分,但这可能会使您的页面加载速度变慢。
回答by Tom B
The 2019 optimal solution for this is HTTP/2 Server Push.
2019 年对此的最佳解决方案是HTTP/2 服务器推送。
You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.
您不需要任何 hacky javascript 解决方案或内联样式。但是,您确实需要一个支持 HTTP 2.0(任何现代服务器版本都可以)的服务器,它本身需要您的服务器运行 SSL。但是,有了 Let's Encrypt,就没有理由不使用 SSL。
My site https://r.je/has a 100/100 score for both mobile and desktop.
我的网站https://r.je/在移动设备和桌面设备上的得分均为 100/100。
The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.
这些错误的原因是浏览器获取 HTML,然后必须等待 CSS 下载后才能呈现页面。使用 HTTP2,您可以同时发送 HTML 和 CSS。
You can use HTTP/2 push by setting the Link header.
您可以通过设置 Link 标头来使用 HTTP/2 推送。
Apache example (.htaccess):
Apache 示例(.htaccess):
Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"
For NGINX you can add the header to your location tag in the server configuration:
对于 NGINX,您可以在服务器配置中将标头添加到您的位置标签:
location = / {
add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}
With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.
设置此标头后,浏览器会同时接收 HTML 和 CSS,从而阻止 CSS 阻止渲染。
You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"
您将需要调整它,以便 CSS 仅在第一个请求时发送,但 Link 标头是“消除渲染阻塞 Javascript 和 CSS”的最完整和最简单的解决方案
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
有关详细讨论,请查看我的帖子:使用 HTTP/2 推送消除渲染阻塞 CSS
回答by tsveti_iko
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Criticalor Critical css for Laravel.
考虑使用包从您的 css 文件自动生成内联样式。一个好的是Laravel 的Grunt Critical或Critical css。
回答by Rajeev
Hi For jQuery You can only use like this
嗨对于 jQuery 你只能这样使用
Use async and type="text/javascript" only
仅使用 async 和 type="text/javascript"