Render blocking and CSS - css

I imagine this has been asked time and time again, but i've not seen the answer I'm looking for.
Im doing some simple tests with a HTML file and CSS file trying to stop the page from render blocking the CSS, running the site through page insights ( google )
Now i've seen answers like this:
<link rel="stylesheet" href="style.20180530.css?ver=1.0" media="none" onload="if(media!='all')media='all'">
and I've seen answers like this:
<link href="https://fonts.googleapis.com/css?family=Roboto:300,700" rel="preload" onload="this.rel='stylesheet';this.removeAttribute('onload');" as="style">
Both of which I am fine with, for the google fonts! But not for the main styles of the page, I don't think its a good user experience to see a page with no styles and then all of a sudden they load in.
Obviously you can eliminate any blocking of CSS by sticking the whole lot as inline styles, but again I don't think this is good practice, you're outputting all styles to a HTML page and not loading them via a style sheet.
I've seen sites actually load the styles like so:
<link rel='stylesheet' id='main-css' href='./style.2018052108.css?ver=4.9' type='text/css' media='all' />
Heres a link to the page insight speed test on the. I know the site is running wordpress. If you view page source it uses the exact same as i've used above.
And they aren't Render Blocking at all... How?
Im on a https I'm using cloudflare and my style sheet is compressed and only around 24bytes and I'm still getting render blocking.
Why?
How to avoid it?

The CSS loaded as an external request is always render blocking, you can't avoid it. The recommendation on pagespeed insights is that you don't do any css request before the content is loaded, in order to avoid the unstyled effect they suggest that you inline the CSS needed to display the content before the fold.
The page on your example is doing exactly that, they inline some css content (check the source code and search for the style tag), then, when the content is loaded they add an external stylesheet with javascript.
All that said, this is a recommendation, you can ignore it if you are happy with the performance of your page, if you want to follow the recommendation you can apply some techniques to achieve this in an automation way.
As always, in css-tricks you have a great introduction post to these techniques: https://css-tricks.com/authoring-critical-fold-css/

The key to the Google PageSpeed insights is above-the-fold render blocking. If you check the site that you linked as your page speed test reference, there are no strictly inline styles - you are correct. However, they have a <style>...</style> block inside of their <head> that sets all of their most important styles for above-the-fold content. That means those styles render immediately, and all other supporting styles will load soon after - but your visitors (and Google PageSpeed) will not notice the difference.

Related

How to use both rel="preload" and rel="stylesheet" for the same tag?

Google Pagespeed test doesn't recognize preload when it is used together with stylesheet. I tried
<link rel="preload stylesheet" href="http://www.example.com/style.css" />
and it still shows "Consider using to prioritize fetching resources that are currently requested later in page load.". If I remove stylesheet from rel attribute, it recognizes the preload.
I was thinking to try this:
<link rel="preload" rel="stylesheet" href="http://www.example.com/style.css" />
but I am not sure if you can have 2 the same attributes for the same link tag. Would this work?
For loading CSS styles asynchronously, you should indicate it, as a preload stylesheet. Whenever you use rel="preload" alone, it won't transform to stylesheet on page load and it will remain as preload, so to indicate it as stylesheet you should use another attribute such as as which indicate the type of element and in your case, it should be style. Then you need to tell the browser whenever the loading process got finished you need to consider this as a stylesheet, so you have to define another attribute like onload and then define its real relation.
so you have to import it like this:
<link rel="preload" as="style" onload="this.rel='stylesheet'" href="http://www.example.com/style.css">
NOTE: You can read more about it here in google developers.
UPDATE
Since preload is not supported in firefox until now (according to this), the only way to do it, is to declare it twice in the one rel tag or two separate tags.
<link rel="preload" as="style" href="http://www.example.com/style.css">
<link rel="stylesheet" href="http://www.example.com/style.css">
Or
<link rel="stylesheet" rel="preload" as="style" href="http://www.example.com/style.css">
NOTE: As #JohnyFree tested the second one (one with a line through) in the Google page speed, it won't be recognized as valid preload style, whilst the format is valid according to W3.org.
preload https://web.dev/defer-non-critical-css/
<link rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'" href="http://www.example.com/style.css"/>
fallback for not supported browsers https://www.filamentgroup.com/lab/load-css-simpler
<link rel="stylesheet" media="print" onload="this.media='all'" href="http://www.example.com/style.css"/>
If you feel you need to do this Javascript circus trick to save a few hundred milliseconds, I recommend the version below. Use it instead if you want cross-browser support:
<link media="print" onload="this.media='all'" rel="stylesheet" type="text/css" href="style.css" />
Why does this work? In nearly all browsers going back to the 1990's, support of linked "print" media type style sheet was universally supported. Linked print style sheets were only used when printing pages. Because browsers knew the "sheet" media type must always be downloaded before "print", they often delayed or downloaded sheets with "media=print" asynchronously. Nothing was needed by the page author. It has worked this way for many years in most browsers, naturally.
Recently, developers trying to follow Google's new ranking policies discovered this trick to stop some styles from blocking others or from downloading immediately. They then realized the "print" media type was the only built-in, cross-browser way to fool browsers into delaying downloading of style sheets.
Turning your style sheet into a "print" type using the trick above doesn't mean its "print", as the script later changes it back to "all". It is simply a "hack" or way to prevent modern browsers from downloading your CSS styles in parallel with other sheets.
Note: "all" is not supported in a wide range of older browsers including Internet Explorer versions 1-7, so a bad idea, anyway.
Stopping one or two style sheets from blocking another sheet from downloading would be the only reason to use this trick, and assumes you are using a HUGE style sheet that is 50+ kilobytes in size and use a server with slow connections.
RECOMMENDATIONS?
I recommend you do NOT ever "preload" CSS for the following reasons!
Just because Google flags this as an issue in Lightspeed, doesn't mean filling your webpages up with duplicate style links and elaborate JavaScript hacks to shave off a 100 milliseconds is a good idea. You should care more about the quality and integrity of your HTML pages above all other concerns, including speed or advertising-driven search engine demands!
There could be racing issues! What happens when your HTML downloads before your async "print" sheet resolves itself back to "all"? You may see a flash in some browsers where the HTML downloads first and rendering begins before the async styles are downloaded. Your user then sees your website layouts and fonts move or shift. Nasty!!
Async'ing CSS is kinda pointless compared to these poorly designed Javascript frameworks kids are downloading in 2021 that waste download times anyway. Most style sheets are 50 kilobytes or less in size compared to the MASSIVE 500-1500+ kilobytes most modern Javascript frameworks shove into the browser today (ie. React, Angular, Ember, etc.). These downloads often "embedd" the same CSS over and over into the browser's cache anyway, forcing a reload of the same CSS each site visit unlike CSS linked styles which can be cached for months! So preloading linked CSS makes no sense if its reloaded every visit. So what is the point?
Many browsers may crash and burn with this trick! The preload is not widely adopted anyway, so you run a huge risk in a percentage of your users
seeing an unstyled web site if you use this "hack". Imagine 5%-10% of your users seeing your website displayed in the default 'Times Roman' font and a white block-level, unstyled content page because you wanted to save 500 milliseconds of download time? Sorry, not worth the risk!
Most old browsers had only 2 open connections allowed when downloading files, so they were limited by open connections, not style sheet downloads. Many modern browsers have 6 maximum. So again, connections are the bottleneck here when combined with multiple open JavaScript calls, not style sheet downloads. So little is gained using this trick.
Slow Servers are Often the REAL Bottleneck: Server delays on opening connections on the server can be huge bottlenecks. Even if your host provider or web application like Wordpress is using cached images, pages, and proxies but your waiting hundreds of milliseconds for a connection to open up on the server, all that becomes meaningless. CDN's can also fail, be delayed, blocked, etc., too.
The number one factor delaying downloads, besides slow servers and giant JavaScript API libraries, is more often huge image files. Consider using new HTML5 'picture' elements with multiple image types like "WebP" that are highly compressed. If you page has "on-demand", non-streaming video, that also must be set to preload or download asynchronously. Adding "width" and height" values to force 'alt' attribute placeholders, as images download will create reserved dimensions in your page layouts so they don't shift waiting images to download. You will be amazed at the savings in download times and bottlenecks prevented when you focus on image and media issues, not CSS.
All that makes preloading CSS pretty worthless as far as website improvements. I would go look at the multiple Bootstrap, JavaScript modules, and JQuery file downloads stacked up in your browser grabbing limited, shared browser connections and focus on less scripts. 30 or so kilobytes of CSS will likely not be the issue.
Firefox has supposedly enabled "preload" in version 85, but it doesn't seem to work correctly. What I found that this code below works:
<link rel="preload stylesheet" as="style" href="style.css">

Improve my site performance

I have a static only site which is hosted on Google App Engine. Infront of this sits Cloudflare CDN.
I have ran Googles Page insights to give me an idea how my website is performing, it is not performing well according to Google. I want Google to see it is performing well for SEO purposes.
This is the report I get from Google:
2 types of recommendations come:
1) Eliminate render-blocking JavaScript and CSS in above-the-fold content
Show how to fix
2) Leverage browser caching
For problem 1 I have tried many things I have read on Google. I have tried adding 'aync defer' to the link attribute. I have tried to make the media = print so that the browser would first render the html then apply the css later. I have tried moving the links to the stylesheets into different locations around the html document. Essentially I have tried to follow this: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery.
As of right now my html page (my website is just on static html page) structure looks like this:
<html>
<head>
<!-- all links/references to css files and javascript files -->
</head>
<body>
</body>
</html>
My second issue is browser caching which I do not understand why I am getting this error. Google App engine caches the files and then on top of that Cloudflare CDN sets the cache headers (and also gzip) on the documents so that the browser caches it (below is the Cloudflare caching components turned on).
I can see the browser is caching the static files and using those cached files in chrome tools when I run the page:
This is really the first time I have created a production static website so I may be misunderstanding many things, but I am looking how eliminate those 2 issues.
Cheers
I don't know if google is measuring this but it is often advised to load Bootstrap and Jquery from the following addresses as they are used by a lot of website and hence are already in browsers caches even if they never visited your website. (The same can certainly be found for font-awesome).
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/YOUR_BOOTSTRAP_VERSION/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/YOUR_BOOTSTRAP_VERSION/js/bootstrap.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/YOUR_JQUERY_VERSION/jquery.min.js"></script>

Google Pagespeed Insight: "Optimize CSS Delivery of the following". How to?

I tested my wordpress website on Google Page Speed Insight and it scored a 95/100. It suggested that I should "Optimize CSS Delivery" of 1 css file:
<link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>" />
Right now it's sitting in the footer along with all the javascript codes below it. I moved it back between the head tag and same results. How do I optimized the css delivery of the css file?
In the case of a large CSS file, you will need to identify and inline the CSS necessary for rendering the above-the-fold content and defer loading the remaining styles until after the above-the-fold content.
Taken from: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
Its not best to actually put all the css together. You should call first the styling that is needed for the rendering and afterwards call that big stylesheet of yours.
And if you want to know how to defer stylesheets well this is how:
CSS delivery optimization: How to defer css loading?
Hope i got you covered :)
95/100 is a great score. You're at the point where more work to hit 100 is going to give you diminishing returns compared to the effort involved with getting there.
But if you're dead set on approaching 100/100 you'll need to remove the above the fold CSS from the file and include it in a <style> block within your theme. Then you can hold off on loading the CSS file until the rest of the page has loaded and it will no longer be render blocking.
Here's some info I wrote on handling above the fold CSS with the WordPress Autoptimize plugin including a JavaScript bookmarklet to get you started with finding your above the fold CSS.
Note: You should be using the wp_enqueue_style() function to include that script, rather than include it directly in the footer. Check out this article on my website to see how to enqueue scripts and styles properly.

"Eliminate render-blocking CSS in above-the-fold content"

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.
But now I find myself glaring at the one remaining yellow dot on the checklist: "Eliminate render-blocking CSS in above-the-fold content".
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.
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
As you can see... ALL of 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... ALL of 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?
A related question has been asked before: What is “above-the-fold content” in 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.
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!
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.
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 ...! ;-)
Addition 1: Here is the page on which Google shows us, what they recommend for 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 design it 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!
Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!
How I got a 99/100 on Google Page Speed (for mobile)
TLDR: Compress and embed your entire css script between your <style></style> tags.
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."
Surely there is an easy solve?? Nope. I tried out Filament group's loadCSS solution. Too much .js for my liking.
What about async attributes for css (like js)? They don't exist.
I was ready to give up. Then it dawned on me. If linking the script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.
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:
postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/ See the NPM postcss package.
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.
I went from 90/100 to 99/100 on mobile!!!
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.
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!
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 will get cached (see Note 1).
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 requireJS you 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.
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 duckduckgo loads for example.
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.
<!-- 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>
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.
Combining all css into one file helped a lot. All my sites are back up to %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.
The 2019 optimal solution for this is HTTP/2 Server Push.
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.
My site https://r.je/ has a 100/100 score for both mobile and desktop.
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.
You can use HTTP/2 push by setting the Link header.
Apache example (.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:
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.
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"
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Shopify: Can't load external stylesheet from another server

https://friends-with-you.myshopify.com/
I'm trying to develop my first shopify theme. I'm trying to load a stylesheet which is hosted on another server, but the CSS is not loading. If I copy and paste that CSS directly into a file in the shopify theme, it works.
<link type="text/css" rel="stylesheet" href="http://fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
What am I doing wrong at the above URL, and why isn't the css loading?
thanks!
Can you load your CSS file over both http and https? If so, change your tag to look like this:
<link type="text/css" rel="stylesheet" href="//fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
That way whether a user visits using http://yourstore.com or https://yourstore.com, they'll get the stylesheet served using the protocol they're on (and you won't get any mixed content warnings).
A little more background: http://paulirish.com/2010/the-protocol-relative-url/
Under IE7 and IE8, using this in a <link> tag will result in your content being fetched twice.
Change your link tag to use a secure URL:
<link type="text/css" rel="stylesheet" href="https://fwy.pagodabox.com/magic/themes/fwy/fwy.css" />
^
The URL you're using now works fine on its own, but since you're browsing to the Shopify store over SSL, many web browsers are going to be hesitant to load the CSS over an unsecured connection.
I just checked and pagodabox serves the CSS file just fine over SSL.
In normal HTML documents one can load stylesheets from anywhere, as long as they exist and you're able to load them by typing the URL in (which I can).
I see the page as two navigation bars with a logo on the left hand side. There are hover states with transitions to a colour background on each item. Although, when I loaded the page, Chrome warned me not to load supposedly insecure content. Before this is loaded I just see text in Times New Roman. I think this is you problem.
I use themes with WordPress and style-sheets come with them (mostly). I don't see why you couldn't just put the style-sheet in with the rest of the theme.
Overall, the answer is yes (normally) but in this case browsers may regard it as un-safe and therefore not load it.
Yes you can! But it is faster to host the stylesheet on your server/where the other files reside. If you plan to include a stylesheet from elsewhere, you could run into problems of that server being down/busy and hence your theme will not display as required. As #Blieque mentioned, some browsers may question external content causing unnecessary warning popups to a user/user-agent.

Resources