Understanding CSS rendering - css

So I read everywhere that CSS is render blocking. Though this is different than the blocking caused by <script> tag as it does not pause parsing of HTML. The browser basically waits for the CSSOM to be constructed and then only render anything to the webpage. Therefore, when CSS is loaded late, it can effect load time for your webpage. But what I don't understand is that if this is the case, how is FOUC (Flash of unstyled content) caused? FOUC is basically when the browser momentarily displays HTML without the styling, and then when the CSS is available, it displays the correctly styled page. So if browser always waits for the CSS to be loaded and parsed first before rendering anything, FOUC should not happen.

if browser always waits for the CSS to be loaded and parsed first before rendering anything, FOUC should not happen.
Indeed, that's what should happen in such a case, except that browsers don't wait for all resources to be loaded before rendering.
Note that this doesn't contradict what you "read everywhere", if you really did read "The browser basically waits for the CSSOM to be constructed and then only render anything to the webpage."
The browser can very well build the CSSOM while it still misses resources, for instance, it definitely doesn't need to load all background-images resources to calculate the elements' box positions.
And it may actually even need to build the CSSOM as soon as the DOM is being constructed because in cases like the below snippet, you need the CSSOM for the js to work:
<h1>test</h1>
<script>
// without CSSOM, we couldn't get its width yet
console.log(document.querySelector('h1').offsetWidth);
</script>
<style>
/* even if it's gonna be invalidated later on */
h1 { width: 300px; border:1px solid; }
</style>

Related

CSS doesn't block rendering on Firefox Quantum

With Firefox Quantum I noticed a "glitch" on loading the CSS of some websites.
One of these is my company's website:
Or Github too:
In the first one, we have only one CSS file in the <head> section of our pages.
It seems that - only in Firefox Quantum - the CSS doesn't block the render of the page as it should. The rest of the page loads without the CSS for some instants, then the CSS is applied as if it loads asynchronously (but it's not).
Obviously, this behavior doesn't happen in all the websites I visited.
I really have no clue what's going on :)
To summarize information from bug 1404468, the "flash of unstyled content" ("FOUC") usually happens when something asks for information depending on styles before the stylesheets are loaded:
Scripts on the page that force layout/style recalc, that are executed before the stylesheets are loaded.
It's recommended to "Put all your styles in and make sure that any script that asks for layout information comes after them".
Be careful with defer scripts, which may execute before the stylesheets are loaded (spec bug).
An iframe that loads faster than parent page's stylesheets forces layout of the parent page for complicated reasons, described in the bug.
Addons (example) which ask for layout information before the styles finished loading (i.e. on run_at: "document_end"). Firefox 60 (2018-05-09) fixed FOUC with the addons that queried layout using run_at: "document_idle", and a few add-ons were fixed around the same time.
Firefox had a bug causing it on sites with autofocus, notably GitHub. Also fixed in Firefox 60.
Factors that do not cause FOUC by itself, but can increase the chances of it being visible:
Firefox 53 reduced nglayout.initialpaint.delay (which delays the initial painting of a page after it stopped being blocked by stylesheets, assuming the HTML is not fully loaded by that time) from 250ms to 5ms.
If the FOUC-causing stylesheets happen to load before the delay, you won't see the unstyled content. With 5ms it became much less likely.
If the HTML page itself loads slowly, you may see some content jumping around the page with more likelihood.
Slow network combined with the factors above increases the chances of seeing the FOUC.
Finally, it's common to see the fonts on the web page "upgrade" to page-provided web fonts, because they don't block the initial rendering by design.
Quick fix that worked for me (from vrancken.gilbert in bug 1404468):
<body>
<script>0</script>
<!-- Your code ... -->
</body>
(...) if you add a dummy script right after your tag FF will only render the page when the CSS is loaded.
Additionnal info :
If you manage the Content-Security-Policy (CSP) in your application (prevents inline-script), it's necessary to white-list this line :
For example :
In your application :
<script nonce="JwkbSbZ2MYNwp5Adp8Nk">0</script>
In your 'Content-Security-Policy' HTTP Header :
(...) script-src 'self' 'nonce-JwkbSbZ2MYNwp5Adp8Nk'
Ref : MDN

When and how do browsers render <style> tag in <body>?

I noticed that if I place <style> inside <body> the css would be applied to all elements after and before <style> tag.
So it looks to me that the css is processed when the page is loaded, similar behavior to javascript document ready event. Am I right? And if that is the case in which order would multiple <style> tags be processed?
TL;DR:
In short, the answer to your question is: once a <style> tag is met inside <body> everything stops and the CSSOM is being rebuilt and re-applied to all existing rendered (painted) content.
Placing <style> tags inside <body> is considered bad practice because it can create FOUC. But if your <style> tag only contains rules for elements placed after it in DOM, placing it in body is perfectly fine, as no FOUC can happen.
The render process of a page is quite complex. But, overly-simplified, here's what happens
<head> is read and CSSOM is built. All CSS is render blocking, unless explicitly specified otherwise by use of #media queries. The non-blocking CSS is still loaded, it's not entirely skipped.
DOM building and CSSOM building are ran in paralel, but all <script> execution is deferred until CSSOM has been built (on </head> tag met), at which point all loaded <script>s are ran, blocking DOM building. JS can make changes to CSSOM at this point. *
Placing <style> tags inside <body> interrupts everything (JS execution and DOM building), CSSOM is being updated and applied to the already rendered content, if any. Everything is resumed after.
* On further testing it appears <head> parsing is single threaded. CSSOM building does block javascript execution but it's done is stages, as each <link /> and <style> tags are met (a <script> placed after a <link> will only execute after the <link /> was resolved and applied to CSSOM). <script> tags placed in between CSS resources are not deferred until all CSS resources in <head> are parsed, as I initially thought.
And, of course js can make changes to CSSOM at run time. See this question I asked for more on how js execution is blocked by CSSOM building.
All the above apply to the normal loading, without considering async, which adds a whole new layer of complexity to it.
If you're interested in more details, I recommend going through the Performance chapter of Web Fundamentals, provided by Google.
Scope of CSS
A style element applies to the whole document, regardless of its position. It is applied as soon as it's loaded.
Reason for putting style tags in <body>
Since every browser has a limited number of threads for downloading a page's files (like JS, CSS, images and asynchronously loaded HTML, JSON or XML), people tend to include CSS files at the end of the body element instead of the classic approach of including them in the head element. This way the rest of the page can be loaded and rendered, and the styling is applied last. You would go this way if your CSS is purely for the looks (i.e. no required element hiding) in order to improve the user experience.
CSS files vs style rules in HTML
Including an external CSS file or putting the same rules in a style element have equivalent results regarding layout and styling. The external file has the downside of a little HTTP overhead, but the benefit of being cached for any further request. If your site consists of more than one page, you usually want to have one or more CSS files that are downloaded only once and re-used for most pages. In addition you can have page-specific rules in another file or within the HTML page.
So it looks to me that the css is processed when the page is loaded, similar behavior to javascript document ready event. Am I right?
No. The stylesheet is modified with the new CSS code when that code is added to the DOM. There's no delay until the rest of the DOM has finished loading. If there was you'd see a FOUC.
which order would multiple <style> tags be processed?
The order they appear in. Then the normal rules of the cascade apply.

setting innerHTML value for <style> does not work in IE7

I'm looking for a way to append styles to my stylesheet dynamically with Javascript.
In today's browsers, I can use this for example:
<style>
#id{background-color:#F00;color:#000;}
</style>
<div ID="id">Test1</div>
<div ID="id2">Test</div>
<script>
document.getElementById('ID').innerHTML+="#id2{color:#00F}";
</script>
The above would change the color of Test from black to blue because of the javascript, but this code does NOT work with older browsers such as Internet Explorer 7.
In Internet Explorer 7, I narrowed the problem down to the fact that it produces a javascript warning symbol at the bottom left corner when it is expected to set the innerHTML value of the style element.
I tried replacing:
document.getElementById('ID').innerHTML+="#id2{color:#00F}";
with:
document.getElementById('ID').appendChild(document.createTextNode("#id2{color:#00F}"));
and I'm still unsuccessful.
I need javascript for this because I want to set the background image for multiple elements at once, and by ramming in CSS code, I can call the image only once. If I used native javascript properties for each element, then I'm going through numerous elements as well as requesting the load of the same element numerous of times, and if IE is bad with caching, then burden will be placed on the server.
What can I do in Javascript to append CSS data to the style element that works with IE 7? I'm looking for something simple.
Well, I went back to the olden days, and managed to pull this off in IE 7:
document.write('<style>'+d+'</style>');
the variable d is the actual rules to insert.
I understand this is a slower method as it creates numerous <style> tags which is bad HTML practice, but the idea works in IE7.

What Exactly Happens When Some CSS Code Found on the Footer

I understand that CSS is used to decide about Layout and other styling things on Web Page. and If CSS is at the bottom of the page then everything (html elements, text, image, etc) will be displayed by using Browser's own styling and when browser find our CSS then it redesign pages again for us. It may be called repainting!
So, I understand that it will look very ugly repainting the page and user seeing it (FOUT - Flash of Unstyled Text - as expert named). But still, I want to understand about:
How much time this repainting can take? Approx value! I understand this can depend on content on the page.
What else happen or can happen?
My main concern right now is about using font-awesome CSS file (externally hosted on their own cdn which download css and font files). I want to know what will happen across devices if I place this at bottom of the page or delay its loading ? Currently it is placed on <head> section as
link rel='stylesheet' href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' type='text/css' media='screen'
Use Del so that it should not look main part of the question. Main part of the question is about Some CSS at the bottom then What will happen to repaint, Blocking, etc. with measurement given or supported by measurement etc.
In the above case or in case when only part of document will get affected by CSS at the bottom then what will happen? Browser repaint everything, and what else? How much time it can take. Suppose, font-awesome is used at 10 icons placed in <i>.
I am never sure of what actually happens when CSS is at the bottom. So, please if you have any video or image showing flow then please mention here.
Base everything on performance across devices, and off course user experience as well. Thank you.
Update: I got something more for myself and for everyone.
Here is a function (delayLoadCss) Google suggest for css for below-the-fold content. Though, I am not going to go that extreme but what about doing that for Font-Awesome kind of CSS?
In my experience the loading of css will be virtually instantaneous no mater where it appear on the page--except in one instance: what will cause a delay in the browser applying your css is placing your css after a script element that takes time to complete.
This is why it is considered best practice to end your body section with your scripts, that way your page is rendered and styled before the browser commits to crunching through your scripts.
So if you html looks like this:
<head>
<link rel="stylesheet" type="text/css" href="/css/styles.css">
<script>
[long loading js]
</script>
</head>
<body>
... content
<script>
[long loading js]
</script>
</body>
Then your css will still be applied right off.
However if you structure it like this:
<head>
<script>
[long loading js]
</script>
<style>
[css here]
</style>
</head>
<body>
... content
<script>
[long loading js]
</script>
</body>
or even
<head>
<script>
[long loading js]
</script>
</head>
<body>
... content
<script>
[long loading js]
</script>
<style>
[css here]
</style>
</body>
Then your css will not be applied to the document until after the js has completed.
The first is best practice and I recomend keeping style tags out of your document completely, but certainly out of the body of your document. External style sheets placed above you script tags is the way to go... This is true for font awesome's externally hosted css also. The browser should not hang on rendering that unless your link to it appears after a script element that is taking up the browsers attention.
* EDIT *
However this post directly contradicts what I just said.
There are two cascades that occur with CSS.
The small Cascade: this is the parsing of an individual style sheet
The Big Cascade: This is where the browser performs three "small cascades", in this order:
User Agent (the web browser's native stylesheet)
Author (the stylesheet that you write)
User (the stylesheet the end user can write).
Your question is about what would happen if you put styles anywhere but the head. Let's discuss:
The browser has its own native stylesheet sitting in the background
The browser loads your HTML document first
The browser then reads the <head>
the browser loads assets in the <head>
the browser parses the rest of the document, i.e. the <body>. assets and style rules located here will be processed last.
the last <style> block, or the last stylesheet in your document is the one whose styles over ride everything else.
In a nutshell, the browser applies styles in the order in which they are seen. A stylesheet at the footer would make things worse, not better. I can't offer a quantifiable measurement of worse because I don't have your stylesheets or website.
All Browsers have FOUC (or FOUT). The duration of it is based on the speed of the browser and the quality of your stylesheet. A minified stylesheet which applies text styles immediately after the reset, and before other styles, usually has the least amount of FOUC.
The styles in the footer are not blocked from being processed, and they will not block styles in the <head>, either. Styles in the footer are simply processed last.
I appreciate the answer from Jeremythuff, however I would also like to answer as well and hope it helps you.
Approx it will take a time to download CSS file (if not cached and not inlined) + a moment. This moment depends on CPU, GPU, HD speeds (if cached) and content + scripts as you have already mentioned. In real practice you do not want to use [link href="..."/] at the end of body because of download time.
You also do not want to use inline styles, because they are not cached and this is yet another piece of code users will download with html, however, this solution can work with small inline styles. In practice it does not produce blinks.
I recommend the following schema:
HEAD > MAIN CSS > BODY > HTML > ADDITIONAL CSS > SCRIPTS
If scripts change default behavior of elements (for example preventing a link from clicking) I recommend to put scripts in head instead.
Now about fonts. In my opinion using external fonts is a bad practice. But if you want, fonts better to include in head because you probably cannot inline them in style tag. So the download time problem occurs here.
10 icons is nothing for nowadays CPUs even on mobile phones.
My advices are straightforward:
(if across devices, I also think of page weight because of slow mobile networks)
Have large additional css (significant difference between the size of html with and without css) - do not include at the end nor as [style]...[/style] (never caches), neither as [link href="..."] (takes download time).
Have small additional css - try with [style]...[/style] at the end of the body before scripts.
Do not worry about 10 icons rendering, worry about download time for 1st visiting users (for fonts).
Your questions are interesting... But there's a problem:
CSS stylesheets must be placed in the <head>!! (except if they are scooped)
Otherwise, your html markup is invalid. Then, every browser could handle it differently.

Overwriting CSS Vs Selectively loading CSS with Modernizer (YepNope)

Unsure how to test this but are there any performance gains from loading in a CSS stylesheet via a query with Modernizer.load as oppose to just overwriting the rule with a CSS classname in the same stylesheet.
For example, if a device has touch support then I have a different layout to load, is it faster to do...
{
test: Modernizr.touch,
yep : 'css/touch.css',
nope: 'css/base.css'
}
Or overwrite the styles in the same stylesheet...
.container { width: 50% }
.touch .container { width: 100% }
Seems the difference comes down to the speed of the extra query Vs the weight of having one big CSS file?
you need to understand you have 3 details here.
the call to the server.
the browser time to calculate all your parent style's
the weight of the files.
so the answer is.
if you write the css without the line break's between the property the 1 big file will be more big from the 2 files. and is answer to the weight cause 1 file is better.
if you have whole page to make with .touch class is more calculate to came the file with the classes.
so, what i'm do is to call to server just one time and make one file cause is better to load all style's together and the call to server (the important time value) will be shortly
I think both options are perfectly valid.
If there's a large amount of CSS code specific to touch, then I would say yes, pull them in with Modernizr to avoid the extra burden on non-touch browsers.
However, my preference would be to generally use override styles for this kind of thing.
The reason for this is that with the Modernizr option, you'll be delaying the loading of the touch styles, because it can't do the Modernizr test until the Modernizr script is loaded and ready to run.
So in comparison to being loaded as part of the main page load and being ready for the initial rendering, it is only loaded after page load, and may not be ready straight away.
The result of this could be that the page may be loaded and displayed before the touch styles are loaded. Not ideal.
This isn't to knock Modernizr -- it's a great tool -- but if you can do what you need to without using it, it's generally better.

Resources