Fastest way to load CSS -- inline vs HEAD - html

I have a 50x50px div I want to display on my homepage as fast as possible.
Is it faster for me to do
<div style="height:50px;width:50px">
Or to assign it a class to avoid the inline style:
<div class="myDiv">
And put the myDiv class in a CSS file in the HEAD section of the HTML page?
My thought was that the first one should be faster since it doesn't need to request and recieve a CSS? I guess ultimatley I'm asking if BODY and HEAD get rendered sequentially or in parallel.

Without HEAD loading first there can be no BODY.
Before your BODY gets rendered, it has has to be loaded first. And if it is loaded, then the HEAD has already been loaded.
You're probably interested in whether a browser can load simultaneously both CSS files and the HTML document itself. It will depend on the browser implementation, but I believe most can download at least two documents simultaneously.
One other important thing is that the more files a document consists of, the more chances the request for one of them gets lost. So by using inline CSS you make sure the CSS never gets lost.
But I must point out that inline CSS is considered a bad style. Once you have a sufficient amount of markup, you will find it increasingly difficult to update your pages all at once. You will inevitably be losing one or the other instance. It is a much better idea to declare all styles in a separate document and reference them from pages. This way, when you need to change some color, you do it in one place and not in 37 places to be found in your pages.

As others already pointed out, the right thing to do would be to put the styles in an external file and refer to it in the <head> part of your document.
But if you're going for fast (and this is what you were asking for) then you should use the inline-declaration like
<div style="height:50px;width:50px">
There are several reasons for that:
You don't have to load an external file. This is very slow (compared to the next reason) since there is an additional HTTP request involved which (on top of the request and download itself) might be held back by other external files like JavaScript, favicons etc.
So it will already load faster if you put your declaration in some <style> tags on the same document. But then there is the next reason.
The browser does not have to look through the DOM tree and search for nodes with the class myDiv to apply the styles to. It finds the <div> and immediately (or at the next render turn) applies the style information.
This second delay will hardly be noticeable but if you are going for high performance, this is the way to go.
I agree that these may somewhat be theoretical reasons but here you go. :-)

There are cases when this would be a "good" practice. For example, you have a high value landing page, that requires about 500 bytes of CSS to support, verses the 200K Style sheet.
While true, that they customer will have to download that file on the NEXT page, time to render is often most important on the landing page.
Also, AFAIK, browsers will not begin rending until the entire CSS file is downloaded, which is not the case for inline styles. But yes, Best Practices, and 98% of the time you want to put CSS in a single linked file.

Use an embeded css file. After the first request the file will be cached by the browser and won't have to be downloaded again. Making the page load faster and reducing the strain on your server.
Placing styles inline is not only ugly it also undermines the whole cascading thing.

The differences in performance will be imperceptible and should be irrelevent. Instead of worrying about premature optimisations like this be more concerned with doing the "right thing" - and in this case the right thing is to use external style-sheet files for your CSS as it is more maintainable and separates concerns.

Related

What happens to unused css rules?

I have a style.css file and almost every component on the website is using rules from this file, but not always for example I have a main template and then a section where requested pages are displayed and of course requested pages sometimes have parts which are unique(not in other pages) and use rules from style.css.
my question is what happens to the css rules that are not used by the current page?
Let's assume that there's a login page and in the login page there's some special button called button_xyz (only exists in login page). The css rule for this button is inside style.css - What happens to this rule when a page, which does not require this rule, is in use?
Does it use extra memory?
Does the browser optimize this for you?
Unused CSS rules probably use a little extra memory, but not on a scale that matters for even the weakest of devices. Some additional time will also be spent parsing the CSS, but not on a level you'd likely be able to even measure.
The main concern about unused CSS rules is that it's wasted bandwidth, but if you only have a few that would be unused on each page I'd say it's best to stick with putting all styles in one file and making sure it gets cached by the browser.
Unless your CSS is drastically inefficient, bandwidth shouldn't be of concern, assuming your server gzips files to send them to your visitors. The bandwidth used really is nothing at all these days. It won't make much difference, but you may also be interested at looking into minifying your CSS, and also HTML and JavaScript while you're at it.
the unused css rules will be a burden for your user who access your website.
because the user first time access your website will download all your css and javascript after that cache it in your web browser. if there are many unused css it size will become big
Css matches your rules based on regular expressions. You have a database inside your browser for exact match, where some kind of hash table works to match exactly name A to name B and since CSS supports Regular Expressions, it can also search with a while loop if regular expression is supplied. For ApplyToAll aka *{ it's also some kind of optimization similar to hash table which applies a rule to everything on the site. So in case you don't have regexes and you don't since in stylesheet they are complex to write, your site won't slow down.

Web Site download speed when using separate CSS file versus HTML style tag

Will a server be able to present a site more quickly if we have all the CSS as part of the style section of the html rather than having a separate linked stylesheet in a separate file?
It is the much better practice to have separate CSS files not only for your organization purposes and for the others who want to later contribute to fix the website but also because this strategy allows you to use the browser's cache.
https://css-tricks.com/one-two-three/
Yes there might be a slight improvement in Load time by having it all on one CSS or even "better" within the same HTML page but there's a reason that basically no sites do that, the reason is that it is basically irrelevant speedwise, it is unconventional and doesn't apply the browser's cache feature.
When using multiple jQuery plugins, with specific css files referencing them:
In that case you may want to use just one separate CSS file for sure, but still better than having a messy giant HTML file with a huge style section.
It also can even be faster in some cases....
Lets say you have an HTML page for the homepage/landingpage /index.html... This has its own style parameters and those are all in the small stylesheet called index.css (for the sake of this example).
The next page is one of the article on the homepage articles.html. It has it's own stylesheet link "articles.css" and that has it's own small rules for style.
If you combined articles.css with index.css then you have a massive file there which will take a long time to load but the user might not even click on article and then they just loaded articles.css's contents for nothing.
This particular site might have a comments link a user link and another dozen pages which the user may never click on. Why force the user to download css files for things they will never see?
When the user clicks on back to return to the homepage ... the other stylesheet is already cached. So it won't matter.
There's a lot to consider when it comes to CSS delivery. Technically inlining CSS is faster, but not always the best practice as it can become tricky to maintain if multiple pages share the same properties.
There's some great articles by Google on this subject:
https://developers.google.com/speed/docs/insights/InlineCSS
https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
You might also want to look into minifying css, as that can slightly improve load times also. Minifying eliminates all spacing and can be inlined or added to an external stylesheet. For example:
div.classy span, div.classy img {
display: block;
border: none !important;
background: none !important;
}
Would become:
dif.classy span,div.classy img{display:block;border:none!important;background:none!important}

Optimize CSS Delivery - a suggestion by Google

Google suggests to use very important CSS inline in head and other CSS inside <noscript><link rel="stylesheet" href="small.css"></noscript>.
This raises few questions in my mind:
How to prioritize CSS in two files. Everything for that page looks important. Display, font etc. If I move it to bottom then how it helps page render. Wont it cause repaint, etc?
Is that CSS is required after Document ready event? Got it from here.
How 'CSS can' go inside <noscript></noscript>, which is for script? Will it work when JavaScript is enabled? Is it browsers compatible?
Reference
Based on my reading of the link given in the question:
Choose which CSS declarations are inlined based on eliminating the Flash-of-Unstyled-Content effect. So, ensure that all page elements are the correct size and colour. (Of course, this will be impossible if you use web-fonts.)
Since the CSS which is not inlined is deferrable, you can load it whenever makes sense. Loading it on DOMContentReady, in my opinion, goes against the point of this optimisation: launching new HTTP requests before the document is completely loaded will potentially slow the rest of the page load. Also, see my next point:
The example shows the CSS in a noscript tag as a fallback. Below the example, the page states
The original small.css is loaded after onload of the page.
i.e. using javascript.
If I could add my own personal opinion to this piece:
this optimisation seems especially harmful to code readability: style sheets don't belong in noscript tags and, as pointed out in the comments, it doesn't pass validation.
It will break any potential future enhancements to HTTP (or other protocol) requests, since the network transaction is hard-coded through javascript.
Finally, under what circumstances would you get a performance gain? Perhaps if your page loads a lot of initially-hidden content; however I would hope that the browser itself is able to optimise the page load better than this hack can.
Take this with a grain of salt, however. I would hesitate to say that Google doesn't know what they're doing.
Edit: note on flash-of-unstyled-content (abbreviated FOUC)
Say you a block of text spanning multiple lines, and includes some text with custom styling, say <span class="my-class">. Now, say that your CSS will set .my-class { font-weight:bold }. If that CSS is not part of the inline style sheet, .my-class will suddenly become bold after the deferred loading has finished. The text block may reflow, and might also change size if it requires an extra line.
So, rather than a flash of totally-unstyled content, you have a flash of partly-styled content.
For this reason you should be careful when considering what CSS is deferred. A safe approach would be to only defer CSS which is used to display content which is itself deferred, for example hidden elements which are displayed after user interaction.

If you have CSS that's specific to that page, is it better to include it in the <head> or a separate file?

I'm working on a web app; one of the screens requires some CSS that's very specific to that page (i.e., it isn't used anywhere else in the app/site).
So - I have three options:
Include it in the global CSS file
Include it in a page-specific CSS file
Include it in the <head> of the page
The downside of option 1 is that the CSS will be loaded when when the user visits any screen of the app, even if she never visits this specific screen (which is quite likely).
The downside of option 2 is that it's a separate HTTP request; since the CSS itself is trivially small (<1kb) - it seems like the overhead of the http request itself is worse than the actual bandwidth to download the data.
The downside of option 3 is that the user will download the CSS every time she visits the page (i.e., the CSS won't get cached). But since this is an infrequently viewed page (and seldomly revisited page), this seems minor.
To me - it seems like option 3 might be the best. But everything I read seems to discourage that approach.
Given how hard experts push CSS sprites to minimize http requests, doesn't the same logic apply to a tiny CSS file? So, why isn't #3 a good option? Are there other considerations I've missed?
For what it's worth - it seems like this same question applies to any page-specific JavaScript; I could include that in a <script> tag at the end of the page, or in a separate .js file.
Thanks in advance.
Put it in the head and move on to other problems. :)
"Programmers waste enormous amounts of time thinking about, or
worrying about, the speed of noncritical parts of their programs, and
these attempts at efficiency actually have a strong negative impact
when debugging and maintenance are considered. We should forget about
small efficiencies, say about 97% of the time: premature optimization
is the root of all evil. Yet we should not pass up our opportunities
in that critical 3%." --Donald Knuth
If you're using it in a single page, you'd best include it in the <head> directly. It results in fewer HTTP requests going through, less bandwidth usage, and marginally faster loading.
You can also consider using a combination of an internal and external stylesheet: for stuff that you might use site-wide, like the styles for h1, h2, h3, and so on, link to an external stylesheet. For stuff specific to the one page, like the background-image, put style in the <head>.

Page-specific css rules - where to put them?

Often when I'm designing a site, I have a need for a specific style to apply to a specific element on a page and I'm absolutely certain it will only ever apply to that element on that page (such as an absolutely positioned button or something). I don't want to resort to inline styles, as I tend to agree with the philosophy that styles be kept separate from markup, so I find myself debating internally where to put the style definition.
I hate to define a specific class or ID in my base css file for a one-time use scenario, and I dread the idea of making page-specific .css files. For the current site I'm working on, I'm considering just putting the style definition at the top of the page in the head element. What would you do?
Look to see if there's a combination of classes which would give you the result that you want. You might also want to consider breaking up the CSS for that one element into a few classes that could be re-used on other elements. This would help minimize the CSS required for your site as a whole.
I would try to avoid page-specific CSS at the top the HTML files since that leaves your CSS fragmented in the event that you want to change the appearance of the site.
For CSS which is really, truely, never to be used on anything else, I would still resort to putting a #id rule in the site-wide CSS.
Since the CSS is linked in from a different file it allows the browsers to cache that file, which reduces your server bandwidth (very) slightly for future loads.
There are four basic cases:
style= attribute. This is the least maintainable but easiest to code. I personally consider use of style= to be a bug.
<style> element at the top of the page. This is slightly better than style= because it keeps the markup clean, however it wastes bandwidth and makes it harder to make sweeping CSS changes, because you can't look at the stylesheet(s) and know what rules exist.
page-specifc css: This lets you have the clean HTML and clean main CSS file. However, it means your client must download lots of little CSS files, which increases bandwidth and page loading latency. It is, however, very easy to maintain.
one big site-wide CSS: The main advantage of one big file is that it's only one thing to download. This is much more efficient in terms of bandwidth and latency.
If you have any server-side programming going on, you might be able to just dynamically combine multiple sheets from #3 to get the effect of #4.
I would recommend one big file, whether you actually maintain it as one file or generate the file through a build process or dynamically on the server. You can specify your selectors using page-specific IDs (always include one, just in case).
As for the answer that was accepted when I wrote this, I disagree with finding a "combination of classes that gives you the result you want". This sounds to me like the classes are identifying a visual style instead of a logical concept. Your classes should be something like "titlebox" and not "red". Then if you need to change the text colour on the user info page, you can say
#userInfoPage .titlebox h1 { color : red; }
Don't start applying classes all over the place because a class currently has a certain appearance that you want. You should put high-level concepts into your page, represented by HTML with classes, and then style those concepts, not the other way around.
I would set an id for a page like
<body id="specific-page"> or <html id="specific-page">
and make use of css override mechanism in the sitewide css file.
I think you should definitely expand the thought process to include some doubt for "page specific css". This should be a very very rare thing to have. I'd say go for the global style sheets anyway, but refactor your css / html in a way that pages don't have to have super-specific styling. And if in the end there's a few lines of page-specific markup in the global css, who cares. It's better to have it in a consistent place anyway.
Defining the style in the consuming page or inlineing your style are two sides of the same coin - in both cases you are using page bandwidth to get the style in there. I don't think one is necessarily better than the other.
I would advocate making an #Selector for it in your site-wide main stylesheet. The pollution is minimal and if you really have that many truly unique cases, you may want to rethink they way you mark-up your sites.
I would put them in a <style /> tag at the top of the page.
It's not worth it to load a page-specific CSS file for one or two specific rules. I would place it in tags in the head of the document. What I usually do is have my site-wide CSS file and then using comments, section it up based on the pages and apply specific rules there.
As you know style-sheet files are static files and cached at client. Also they can be compressed by web server. So putting them in an external file is my choice.
For that situation, I think putting the page-specific style information in the header is probably the best solution. Polluting your site-wide style sheet seems wrong, and I agree with your take on inline styles.
In that case I typically place it at the top of the page. I have a page definition framework in PHP that I use which carries local variables for each page, one of which is page-specific CSS styles.
Put it in the place you would look if you wanted to know where the style was defined.
For me, that's exactly the same place as I would place styles that were used 2 times, 5 times, or 170 times - I see no reason to exclude styles from the main stylesheet(s) based on number of uses.