#import or <link> for importing stylesheets? - css

Which method is best for importing multiple stylesheets? Is one method more efficient than the other?

I once read this article about performances and <link> vs #import : don’t use #import ; quoting a small portion of it :
use LINK instead of #import if you
want stylesheets to download in
parallel resulting in a faster page.
It's quite recent (April 2009), so should still be mostly true -- and written by Steve Souders, whose name is quite well-known when it comes to front-end performances.
On a more subjective point, I quite prefer using several <link> from my main HTML file : this way, I am able to see in only a quick glance what css files are called -- either looking at the template file on the server, or looking at the generated HTML source on the client side.

On some (all?) implementations #import is processed at the end of the loading of the page, so you'd have the undesired Flash of Unstyled Content using it.
link works usually better, but if what you wan't is to define a different media, you could use it without problem. Also, its a neat trick to hide CSS from older browsers (<IE5.5).

Related

alternative way to include external sylesheets rather than #import?

So, documentation has shown that using #import on stylesheets is a bit slower, and plus it makes extra server calls.
Example:
#import url('narf.css');
Well, I HATE using one giant stylesheet, it is messy. I am a neat freak when it comes to my code. hahaha.
Anyway, I use dreamweaver for my design, but it does not "respond" to using regular includes to include another stylesheet (even with boilerplate). Basically, you cannot access the "included" styles when you are designing.
These do not work when using Dreamweaver (although they may work on the server).
<!--#include file="narf.css" -->
<?php include('narf.css'); ?>
So, I ask, are there any other alternatives to actually USE the styles during the design process and still keep the server requests down? I appreciate any insight you may be able to share.
Thank you again overflow community!
You could just have multiple stylesheets, and concatenate your stylesheets for production, that way you can separate your stylesheets, and keep the server requests to a minimum.

#import usage for structuring css

Im just trying to confirm if I understood #import correctly,
Basically what It can do for you probably at least one of the things is to give your css some structure by separating the different layouts in separate categories.
Right now each of my css files look insane, I have about 10 of them for one site and alot of them are using up space for the same code and only some new stuff have been added.
I am guessing that I can use #import to only add style where it is needed?
Yes, it works pretty much like include or require functions in PHP.
You can separate your style in multiple files and include some of them where it's needed.
Unlike PHP, CSS use HTTP requests to import files, which means your site will be slow if you separate your CSS to many files (try to keep it up to 3, but only 1 is ideal).
I suggest you to separate files only during the development period which would allow you to manage your files easier, but put everything into 1 file before launching your site.

Does using #import in a CSS file cut down on HTTP request?

If I have a CSS file that is included into the page like
<link rel="stylesheet" type="text/css" href="all.css">
And then that file has...
#import "shCore.scss";
#import "shThemeDjango.scss";
Does this do 1 HTTP request or 3?
Is there a benefit of importing multiple files vs linking to all of them in the main file?
(I know the ideal solution is to combine all and minify)
I would recommend not using #import. This stops the browser from downloading files in parallel as it has to parse the first css file. Then go retrieve the import css files and import them.
google on #import
As you mentioned combining and minifying your css is the best option. Using a tool like minify allows you to keep your stylesheets separate and clean but serve them combined and minified.
This would still mean three HTTP-request, and there it most likely make the load process even slower, as Jros mention.
Instead I suggest that you minify all your CSS into one file, to make as few HTTP-requests as possible, and to decrease the amount of data that needs to be transferred.
Here's an example of a CSS minifying tool you can use, if you don't want to do it server-side.
I think, given the context of the question, there has been some misleading advice. Sure, "vanilla" CSS #import will make a HTTP request. But the OP seems to be using a pre-processor.
Pre-processors, such as; SASS or LESS, work by compiling down your code, often into a singular css file. Meaning an #import has already been handled and included for you. You just reference the end-point stylesheet.
So no. Knock yourself out, when using a pre-processor. It's a great way to organise your code.

Comparison of loading CSS inline, embedded and from external files

We can write CSS as the following types:
Inline CSS
Embedded CSS
External CSS
I would like to know pros and cons of each.
It's all about where in the pipeline you need the CSS as I see it.
1. inline css
Pros: Great for quick fixes/prototyping and simple tests without having to swap back and forth between the .css document and the actual HTML file.
Pros: Many email clients do NOT allow the use of external .css referencing because of possible spam/abuse. Embedding might help.
Cons: Fills up HTML space/takes bandwidth, not resuable accross pages - not even IFRAMES.
2. embedded css
Pros: Same as above regarding prototype, but easier to cut out of the final prototype and put into an external file when templates are done.
Cons: Some email clients do not allow styles in the [head] as the head-tags are removed by most webmail clients.
3. external css
Pros: Easy to maintain and reuse across websites with more than 1 page.
Pros: Cacheable = less bandwidth = faster page rendering after second page load
Pros: External files including .css can be hosted on CDN's and thereby making less requests the the firewall/webserver hosting the HTML pages (if on different hosts).
Pros: Compilable, you could automatically remove all of the unused space from the final build, just as jQuery has a developer version and a compressed version = faster download = faster user experience + less bandwidth use = faster internet! (we like!!!)
Cons: Normally removed from HTML mails = messy HTML layout.
Cons: Makes an extra HTTP request per file = more resources used in the Firewalls/routers.
I hope you could use some of this?
I'm going to submit the opinion that external style sheets are the only way to go.
inline CSS mixes content with presentation and leads to an awful mess.
embedded CSS gets loaded with every page request, changes cannot be shared across pages, and the content cannot be cached.
I have nothing against either method per se, but if planning a new site or application, you should plan for external style sheets.
Inline
Quick, but very dirty
This is (sadly) also the only really sane option for HTML formatted email as other forms often get discarded by various email clients.
Embedded
Doesn't require an extra HTTP request, but doesn't have the benefits of:
Linked
Can be cached, reused between pages, more easily tested with validators.
You want external css. It's the easiest to maintain, external css also simplifies caching. Embedded means that each separate html file will need to have it's own css, meaning bigger file size and lots of headaches when changing the css. Inline css is even harder to maintain.
External css is the way to go.
Where to start!!??
Say you had a site with 3 pages...
You could get away with Inline CSS (i.e. CSS on the page itself, within tags).
If you had a 100 page website...
You wouldn't want to change the CSS on each page individually (or would you?!)...
So including an external CSS sheet would be the nicer way to go.
Inline CSS is generally bad. It's much easier to modify the style of a page when all the styles are located in one central location, which inline CSS doesn't offer. It's easy for quickly prototyping styles, but shouldn't be used in production, especailly since it often leads to duplicating styles.
Embedded CSS centralizes the styles for the page, but it doesn't allow you to share styles across pages without copying the text of the embedded style and pasting it in each unique page on your site.
External CSS is the way to go, it has all of the advantages of embedded CSS but it allows you to share styles accross multiple pages.
Use external CSS when:
you have a lot of css code that will make your file messy if you put it all inline
you want to maintain a standard
look-and-feel across multiple pages
External CSS makes it a lot easier to manage your CSS and is the accepted way of implementing styles.
If the styles are only needed for one file, and you don't foresee that ever changing to apply to other pages, you can put your css at the top of the file (embedded?).
You should generally only use inline CSS if:
It's a one-time formatting for a specific tag
You want to override the default css (set externally or at the top of the file) for a specific tag
To everyone in the here and now, reading after 2015, with projects like Polymer, Browserify, Webpack, Babel, and many other important participants that I'm probably missing, we have been ushered into a new era of writing HTML applications, with regards to how we modularize large applications, distribute changes and compose related presentation, markup and behavior into self-contained units. Let's not even get started with service workers.
So before anyone forms an opinion on what is and isn't feasible, I would recommend that they investigate the current web ecosystem in their time to see if some issues related to maintainability have been gracefully solved.
Pros:
Allows you to control the layout of the entire site with one file.
Changes affect all documents at the same time.
Can eliminate redundant in-line styling (Font, Bold, Color, Images)
Provide multiple views of the same content for different types of users.
Cons:
Older browsers may not be able to understand CSS.
CSS is not supported by every browser equally.
In this case, the pros far outweigh the cons. In fact, if the site is designed in a specific way, older browsers will display the content much better (on average) than if the site were managed with tables.
If you are using a server side language, why not embed CSS and use conditional programming to display it as necessary? For example, say you're using PHP w/ Wordpress and you want some homepage specific CSS; you could use the is_home() function to show your CSS in the head of the document for that page only. Personally, I have my own template system that works like so:
inc.header.php = all the header stuff, and where page specific CSS would go I put:
if(isset($CSS)) echo $CSS;
Then, in a specific page template (say about.php), I would use a heredoc variable for the page specific CSS, above the line which includes the header:
Contents of about.php:
<?php
$CSS = <<< CSS
.about-us-photo-box{
/* CSS code */
}
.about-us-something-else{
/* more CSS code */
}
CSS;
include "inc.header.php"; // this file includes if(isset($CSS)) echo $CSS; where page-specific CSS would go ...
<body>
<!-- about us html -->
include "inc.footer.php";
?>
Is there something I'm missing that makes this approach inferior?
Pros:
1) I can still cache the page using standard caching techniques (is there a caching method that takes advantage of a CSS only external file??).
2) I can use php for special case conditional formatting in specific class declarations if absolutely necessary (PHP doesn't work in a CSS file, unless I'm missing some server directive I could set).
3) All my page specific CSS is extremely well organized in the actual PHP file in which it's being used.
4) It cuts down on HTTP requests to external files.
5) It cuts down on server requests to external files.
Cons:
1) My IDE program (Komodo IDE) can't follow the Heredoc formatting to properly highlight the CSS, which makes it slightly harder to debug syntax errors in the CSS.
2) I really can't see any other con, please enlighten me!

IE Question: How many CSS includes can it handle?

I came across a strange behavior while theming Drupal. I turned a few modules that added 5 to 10 link tags to the page. While these new stylesheets were added to the cascade in Firefox, in IE8, by adding these the browser discarded the earlier added CSS files from the hierarchy. In fact, the first files were the first to go, which completely screwed up the styling of the page and had me scratching my head for a while. Eventually I discovered the newly added modules had caused IE to pass some internal threshold where it could not add new includes anymore.
Has anyone seen this behavior before? I'm not sure if it's an issue with browser or with my setup.
Internet Explorer has a maximum limit of 32 CSS file links. Definitely a browser issue. You'll need to think about consolidating your css requests.
Generally you can do this by concatenating them if they're static files, but if you're generating them programatically, you might have to look at a solution to manipulate the response before it gets passed to the browser.
We had to get around this issue for our enterprise ASP.Net project and ended up writing a "Css Multiplexor" that examined the response, found the requested CSS links, generated a web resource for one big css file, and output a link to that instead.
I encountered this issue on our site.
IE8 only permits 32 CSS imports per file. That file could be an HTML file or a CSS file. (*) However, the import limit does not restrict you to 32 CSS files total. You can link to two CSS files in your HTML, each of which #imports 32 CSS files. Playing with tricks like that should get you as many as you need.
The specific workaround we use is to split the CSS files we need into two groups, and have two 'import' CSS files. The HTML page imports the first import CSS file, which imports the first group and the second import CSS file, which imports the second group.
This works fine, but results in lots of HTTP requests, so we only use this workaround on development systems. For our live sites we have a build step that compiles all the CSS into one file.
What Johannes has mentioned -- getting Drupal to aggregate your CSS -- sounds like the best bet.
(*) There's some fine print like: the 32 imports includes the CSS files that have already been imported in the chain from your HTML page. So if your HTML imports a CSS file, then that CSS file can only import 31 other second-tier CSS files, and each second-tier CSS file can only import 30 other third-tier CSS files. You really have to wonder what bizarre algorithm causes this limitation...
The limit is 31 - NOT 32!
While some would say "who cares, close enough, right?" --- With larger applications with hundreds of developers it can be very easy for the page to go over the limit, so you should really know the exact number of css stylesheets can be included on the page.
There are several ways to mitigate the problem:
Reduce the number of CSS files by consolidating into larger files - perhaps manually, or some run time grouping mechanism, or you can use an automated css compiler to combine and minimize all your CSS files
Use #import url(...) statements rather than <link href=""> but remember you can only have 31 #import (again, NOT 32...) statements in one stylesheet
Use #2 above with caution because:
You are only increasing the limit (to 961 css files) not removing it
The browser will be forced to download the CSS files in series rather than in parellel. Normally a browser can download more than 1 css file at a time (the count depends on if the files are in the same domain and which browser you are using) - This can have a significant impact on performance.
Each CSS file requires a round trip to the server adding extra time.

Resources