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

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.

Related

Why are my stylesheets with media="all" getting listed as render-blocking resources?

In the PageSpeed Insight report for my site, it's listing all of my css files as "render-blocking resources". My css links all look like this:
<link rel="stylesheet" type="text/css" media="all" href="https://example.com/something.css" />
In the documentation, it says <link rel="stylesheet"> tags are listed as render-blocking stylesheets if they don't have a media attribute that matches the user's device. Since my stylesheets all have media="all", why are they getting listed as render-blocking resources?
The documentation is very misleading.
What they are trying to say is they will not flag something as render blocking if you have a media query that matches the users device only (so a max or min width or an orientation for example).
However even then they will flag it under 'critical CSS' and even if they don't flag it, it is still render blocking if that CSS is required for the 'above the fold' content.
Further down the page you linked in your question they explain it slightly better
Another approach to eliminating render-blocking styles is to split up
those styles into different files, organized by media query. Then add
a media attribute to each stylesheet link. When loading a page, the
browser only blocks the first paint to retrieve the stylesheets that
match the user's device.
That part is the important part, they are trying to get you to put your mobile styles in one style sheet, desktop in another so you only load the bear minimum CSS to render the page initially.
What really matters
Ignore all the confusing stuff, here is the simplest way to tackle a few audits at once.
Inline your critical CSS - the only step you really need
Any CSS that is required to render the 'above the fold' content should be inlined within your HTML within a style tag.
I will warn you, this is difficult, none of the tools out there do this perfectly and it must have every single style rule included to work. (e.g. if you missed just one class that is required to render something 'above the fold' the browser will wait for the style sheet that contains that rule to be loaded and block the rendering.)
Designing for this from the start is the best option
I keep all my 'above the fold' styles in a separate file and inline them at runtime.
I split these files into 2 types - global (site header, general styles used on multiple pages above the fold etc.) and page-specific (e.g. hero for home page, form styling for contact forms etc... whatever is 'above the fold' on each page that is unique enough to not add to the global above the fold styles.)
This will deal with render blocking resources, critical request chains (for CSS) and give you super fast First Contentful Paint and First Meaningful Paint.
Then you just do as they suggest having styles for mobile and desktop separate and make sure you remove unused CSS if you can (yet again a very difficult task so best to design for it from the start).

Understanding CSS rendering

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>

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.

Is it bad practice to use inline css in asp.net?

I am new in css. My project is Layout Manager. Most of the time I use inline css. When I showed my project to the project head, he said to reduce inline css.
Is inline css really bad for project? Please help to clear my vision.
Inline CSS is bad, period. It does not matter which framework you're using. In addition to bloating the document (and potentially slowing load time), it also makes it a lot harder to figure out where the heck values are being set -- as a general rule HTML is dynamic and CSS rarely is. This means if you want to change a style value, you are probably looking at one, flat CSS file, instead of a potentially massive codebase.
I am new in css
No, you are new to wweb programming. You can not say you did HTML etc. without touching CSS at all ;)
My project is Layout Manager
Which tells us nothing.
Is inline css really bad for project?
no, it has zero implications for your project.
It normally is a maintenance problem (not if auto generated). It's main issue is waste of bandwidth because inline CSS have to be on every page instead of being on a seaprate file loaded only once for all pages in the site. Dependingon size and traffic this can be SIGNIFICANT.
the reasons why should avoid inlines css
a) Separation of concerns - your markup should contain only markup code and all you rhutehr hunky dory code should be in separate files like js and css.One of the main goals of CSS is to remove the design elements from the HTML and place them in another location for the designer to maintain. That means that a designer doesn't have to also be the content developer to maintain the look of the Web site.
b) Caching of Files when you have your js and css in separate files the browsers starts caching this till something has changed on the server and this means less data transmitted between the server and the client thus saving up on b/w and the page loading faster for your viewers..
c)Make maintenance easy
One of the most forgotten elements of Web design is the maintenance. Things change - from the look of your site to the content and links within it. And having your CSS in a central place makes it that much easier to maintain.
d)Keep your site accessibile
Using CSS styles can keep your site more accessible both to disabled people and to robots like search engines.
e)Your site will stay current longer
By using best practices with your CSS, you're using standards that have been proven to work and remain flexible as the Web design environment changes.
In this case the style will be loaded before the page loads.
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="anyClass">Hello</div>
</body>
</html>
But if we use the following, browser will be interrupted during parsing every specific style defined inline the style attribute, so this will slowdown load-time:
<html>
<body>
<div style="height: 70px;">Hello</div>
</body>
</html>
Also, placing the style in a separate style-sheet will help you reusing the styles and maintenance of the code will be easier.
Inline CSS is bad or good depending on what you will achieve in the project in the future.
For example take this two general cases:
If the css that you define inline will be used again then using inline is bad, just add it to a css file and reuse it every time you need in the future.
If the inline you are using is an one time exception then it is a good solution and there is no point in overcomplicating design by placing it in a separate css file.
It is a good practice to separate HTML, css and javascript in separate files and because you are new to web programming, you can make this practice easily from the beginning.
The disadvantages of inline CSS are:
Significant usage of bandwidth.
Cannot use a style on multiple documents.
Cannot implement pseudo-elements and pseudo-classes in inline styles.
Cannot create neat and clean HTML with inline css.

Performance implications for overriding CSS styles

I'm setting up an image cluster for a webpage (similar to sprite-map) for performance reasons. I have a utility that generates the master image, and css to reference the image map.
For simplicity sake, I'd rather include the new css after the regular css file, instead of writing a script to search and replace all the classes in the original css. Something like so in the html (psuedo code):
<LINK href="normal.css" rel="stylesheet" type="text/css">
if(%=usingImageCluster=%)
<LINK href="master.css" rel="stylesheet" type="text/css">
So all the styles that are defined in normal.css would get overridden by the new styles in master.css.
Couple of questions:
Besides the "duplication" of information, does this override cause performance issues?
Will the browser still pull the non-clustered images, because the original CSS file is still included (negating the positive performance gains of image clustering)?
Is there a guarantee that the last loaded style will always be the one applied?
Besides the "duplication" of information, does this override cause performance issues?
Yes, you are generating a new HTTP request for the second external stylesheet. Too many HTTP requests is the #1 slowdown factor for most webpages.
Will the browser still pull the non-clustered images, because the original CSS file is still included (negating the positive performance gains of image clustering)?
Yes, the browser will pull ALL images from the first and second CSS file. Performance time will increase almost linearly (approximate). Especially if you are rewriting every css selector, or changing lots of images.
Is there a guarantee that the last loaded style will always be the one applied?
Yes. Unless the first sheet uses !important on certain style attributes, the last declared styles for a selector will always be applied. This is where Cascading Style Sheets get their name.

Resources