Should i always use external style sheet even if the style is for one particular page - css

Since External Style Sheet will be kept in cache, so it will be faster for page load with frequenly visit.Should i always using external style sheet instead of embedded style sheet even if a style is used only for one particular page. The only drawback i can think of is if we use only external style sheet we might have a lot of file in folders styles and this can be messy and confused for others fellow developer compared with using embedded style sheet for css that use only on that page.

If it's for one page, and only that page, then no. You'll induce an unnecessary GET request on your server to grab that CSS file.
Edit: To answer the question in your comment "Will using an external CSS document have an overhead of a GET request?" the answer is yes. For each file not included in the HTML document you're accessing (i.e. external javascript files, images, external stylesheets, etc) the client's browser will have to make another GET request to attain those files.
An embedded CSS is included in the first GET response for that page (it is part of the HTML response, after all).
In external style-sheet case scenario, you'd be imposing two GET requests (one for the HTML document, and another for the CSS file) as opposed to the single GET request to just embed the CSS into your document.
See the wiki on HTTP for more information: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_message

HTTP requests are costly as far as speed goes. I'd try to minimize them. For organization sake, try to keep things in external stylesheets, but if it's just a couple of things applicable to only that page, it makes sense to use an embedded stylesheet. You have to find the right balance of the two.

Related

CSS embeded within dwt vs external style sheet

I created a new website with 46 pages: http://www.lampshade111.com/
I use Microsoft Expression Web 4 employing a dynamic web template.
All css was embedded within the heading of the dwt page and updated to every individual web page.
Everything looks and works perfectly - no problems.
However, everything I have read suggests using an external style sheet.
So in the spirit of "good practice", I removed css from the dwt heading and employed (linked) an external style sheet to the dwt.
Of course the individual pages are updated by the dwt and the linked css file is shown on every page.
Again, everything looks and works perfectly as before.
Problem: When viewing my website after employing an external style sheet, the website is much slower in my browser.
I have another website with 256 pages and all css is embedded within the heading of the master dwt - no external style sheet.
http://www.hoylelamps.com/
It has worked fine for many years.
Questions:
Is there any reason to not use css in the heading of a dwt ?
Is this suppose to be more efficient (faster) than an external style sheet ?
I cannot find any information on this subject.
Thanks for any help ? - Jim
I can't imagine why an external style sheet is "much slower" than an external one. A linked style sheet will be cached as soon as it is loaded and will not have to be loaded a second time. That means the second and third pages you load should be faster, unless you are using totally different formatting on each page.
Embedded style sheets will run faster at first, because only one resource has to be loaded. But over time the work needed to maintain multiple pages with embedded style sheets will be much more of a burden. Remember every time you change even one CSS rule in any page, you will have to make that change in every single page and upload all those pages again. If you don't, you will have individual pages formatted differently throughout the site.
An external linked style sheet precludes this problem. One style sheet, one file to correct and to upload. The only things I can think of that would make your page load or respond more slowly are the following:
Very large style sheet
Using "import" instead of "link" command (some browsers react differently to these commands)
You are using non-standard CSS or very dense styling commands.
Without seeing the CSS I really can't give you any more suggestions. The fact that the browser has to load two files at first, will cause it to function slightly slower. But it's hard to understand why the entire site runs more slowly.
Here are some suggestions:
Have you checked and tested your pages in other browsers and other computers? Maybe it's not the page at all. Maybe it's the browser or the computer you are using.
If your style sheet is large, break it into logical components. I have style sheets that format tables, forms and special components that don't appear on every page. Load only the CSS that is pertinent to that page. Have one main style sheet and then specialized style sheets for specific types of components, like those mentioned.
Check the types of commands you are using. Are you making best advantage of Cascade, Inheritance, and specificity? Try to create CSS that is as efficient as possible.
Keeping embedded style sheets may be easy at first, but updating and maintaining a large website with embedded style sheets would be much more burdensome.
Hope that helps.

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!

CSS on a separate file or not?

Which is a better option: to store CSS on a separate file or on the same page?
Let's forget the fact that changing the CSS on a file makes it to apply all HTML pages directly. I am using dynamic languages to generate the whole output - so that does not matter.
A few things I can think of:
CSS on a separate file generates less bandwidth load.
CSS on a separate file needs another HTTP request.
On the other hand, if I compress the data transmission with Zlib, the CSS on the same page should not matter in terms of bandwidth, correct? So, I get one less HTTP request?
The main benefit of an external CSS file is that:
It can be used on multiple pages; and
It can be cached so it doesn't need to be loaded on every page.
So, if there is potential for reuse of the dynamically generated CSS between pages or on multiple views of the same page then an external file could add value.
There are several common patterns for dynamically generated CSS.
1. Generating a subset for a page
I've seen this occasionally. A developer decides to limit the amount of CSS per page by only sending what's necessary. I don't imagine this is the case for you but I'm mentioning it for completeness. This is a misguided effort at optimization. It's cheaper to send the whole lot and just cache it effectively.
2. User-selected theme
If the user selects a particular look for your site, that's what I'm talking about. This implies they might select a whole package of CSS and there might be a limited set to choose from. Usually this will be done by having one or more base CSS files and then oen or more theme CSS files. The best solution here is to send the right combination of external CSS files by dynamically generating the page header with the right <link> elements and then caching those files effectively.
3. User-rolled theme
This goes beyond (2) to where the user can select, say, colours, fonts and sizes to the point where you can't package those choices into a single theme bundle but you have to generate a set of CSS for that user. In this case you will probably still have some common CSS. Send that as an external CSS files (again, caching them effectively).
The dynamic content may be best on the page or you may still be able to make use of external files because there is no reason a <link> can't point to a script instead of a static file. For example:
<link rel="stylesheet" href="/css/custom.php?user=bob" type="text/css">
where the query string is generated dynamically by your header from who is logged in. That script will look up the user preferences and generate a dynamic CSS file. This can be cached effectively whereas putting it directly in the HTML file can't be (unless the whole HTML file can be cached effectively).
4. Rules-based CSS generation
I've written a reporting system before that took a lot of rules specified by either the user or a report writer and a custom report and generated a complete HTML page (based on the tables and/or charts they requested in the custom report definition) and styled them according to the rules. This truly was dynamic CSS. Thing is, there is potential for caching here too. The HTML page generates a dynamic link like this:
<link rel="stylesheet" href="/css/report.annual-sales.0001.css" type="text/css">
where 'annual-sales' is the report ID and 0001 is like a version. When the rules change you create a new version and each version for each report can be cached effectively.
Conclusion
So I can't say definitively whether external CSS files are appropriate or not to you but having seen and developed for each of the scenarios above I have a hard time believing that you can't get some form of caching out of your CSS at which point it should be external.
I've written about the issue of effective CSS in Supercharging CSS in PHP but the principles and techniques apply in any language, not just PHP.
You may also want to refer to the related question Multiple javascript/css files: best practices?
There is a method that both Google and Yahoo apply which benefit's from inline CSS. For the very first time visitors for the sake of fast loading, they embed CSS (and even JavaScript) in the HTML, and then in the background download the separate CSS and JS files for the next time.
Steve Souders (Yahoo!) writes the following:
[...] the best solution generally is
to deploy the JavaScript and CSS as
external files. The only exception
I’ve seen where inlining is preferable
is with home pages, such as Yahoo!'s
front page (http://www.yahoo.com) and
My Yahoo! (http://my.yahoo.com). Home
pages that have few (perhaps only one)
page view per session may find that
inlining JavaScript and CSS results in
faster end-user response times.
If you're generating HTML dynamically (say, from templates), embedding CSS allows you the opportunity to also generate the CSS dynamically using the same context (data, program state) as you have when you're producing the HTML, rather than having to set that same context up again on a subsequent request to generate the CSS.
For example, consider a page that uses one of several hundred images for a background, depending on some state that's expensive to compute. You could
List all of the several hundred images in rules in a seperate, static CSS file, then generate a corresponding class name in your dynamic HTML, or
Generate the HTML with a single class name, then on a subsequent request generate CSS with a rule for that name that uses the desired image, or
Do (2), but generate the CSS embedded in the HTML in a single request
(1) avoids redoing the expensive state computation, but takes a larger hit on traffic (more packets to move a much larger CSS file). (2) Does the state calculation twice, but serves up a smaller CSS file. Only (3) does the state calculation once and serves the result in a single HTTP request.
Browsers can cache the CSS files (unless it changes a lot). The bandwidth should not change, because the information is sent, no matter where you put it.
So unless the css quite static, putting it in the page costs less time to get.
I always use mix of both.
site-wide styles are in separate file (minified & gzipped),
any page-specific styles are put in <style> (I've set up my page templates to make it easy to insert bits of CSS in <head> easily at any time).
Yes and no. Use a .css file for most rules; your site should have a consistent look anyway. For rare, special case, or dynamically generated rules you can use inline 'style=""'. Anything that sticks should move into the .css, if only to make transcluding, mash-ups, etc. easier.
Keep it separate. HTML for centent, CSS for style, JavaScript for logic.

Does #import in CSS result in additional http requests?

I have an ecommerce site that has about 8 CSS files linked from the header - resulting in 8 separate http requests to the server. I consolidated all the CSS files into 1 big one, resulting in a 67kb (!) file - to cut down the http requests to 1 for our css files.
I'm finding this size a CSS file a little unmanageable in light of the fact I'm performing updates on the site constantly. My concern is my users may catch me in the middle of updating and see a NON-styled page when moving from page to page - b/c 67kb still takes a good 2-3 seconds before it is successfully placed on the remote server via FTP.
My question is: does the use of #import within this large CSS file to break up the files into smaller more manageable sizes (within that CSS file) take us back to the original 8 http-requests when the pages is loaded? Or are #imports in CSS handle differently somehow?
Yeah you will go back to a request per each stylesheet while using #import.
Your best bet is to minify and consolidate the css into a single file for deployment. But you can still develop with seperate files.
You can prevent the extra http requests by combining the stylesheets with .htaccess. The technique is explained in the HTML5 Boilerplate .htaccess. It works like this:
In .htaccess:
<FilesMatch "\.combined\.(js|css)$">
Options +Includes
SetOutputFilter INCLUDES
</FilesMatch>
In style.combined.css:
<!--#include file="reset.css"-->
<!--#include file="style.css"-->
You can use this to combine .js (or any other extension you put in the parenthesis.)
The documentation for Options +Includes is here.
The browser has to get the data somehow, so how could it not use another http request? ;-)
It's also possible though, that you'll benefit from browser caching if you're only changing one file and the other seven are unchanged.
You might try sniffing a connection between a client and the server and see what it requests.
Yes, a separate request is issued for each #import statement.
You can check this with a quick test; write a fragment of HTML, including a CSS file which imports a second CSS file. Viewing the results in something like Firebug's network panel shows two separate requests for each CSS file. That's the test I used to confirm this answer.
CSS imports are not handled any differently than any other "include" on a page, such as a reference to an external JavaScript script. However, browser caching should make this a non-issue except for the first access to your site.
If you have a 67 Kb CSS file there is something strange. Remember that the C in CSS is for CASCADING, and this means that you don't have to define in each class all the properties of each one of the tags involved in the class.
For example if you define a <DIV id="maincontainer"> as a container you can define a class to it
#maincontainer {font-face:Arial,helvetica,sans;}
It means that if you create a sub-class of it for the tag <P> like
#maincontainer P {color:darkgray;}
All the <P> tags inside the DIV maincontainer will use font arial, helvetica, sanz.
Also try to create CSS files in order to how them are used in the pages. A unique CSS file for all the site makes to load a lot of classes that are not going to be used in some pages. Divide and conquer.

Internal vs External CSS

What's the pros and cons on Internal vs External CSS, thinking of speed, requests, caching etc..? Personally I'm not sure if internal css on dynamic pages will cache..?
Pros for internal CSS:
- faster downloads: remember that there will be one additional HTTP request for each external style sheet you have
Pros for external CSS:
- it is common for websites to have common 'theme' across all its pages. You can club all such common styles in external file and with one download you get the required style that can be used in multiple pages: saves download time
- you can also cache external styles and set an appropriate expiry date.
One thing against for internal CSS is that it can increase the download size of the html.
Best approach:
- use mix of internal + external styles depending on which styles are used in diff pages
- make sure to set expiry settings on external styles and cache them.
Advantage of combining with Cache expiry settings:
"Look and feel" of web apps is governed by the following:
you typically want to maintain same 'feel' across all pages
the content is more likely to change frequently than the styling
If you put styles in external CSS file and set a cache expiry of say 1 month, then during this time all users will have very low 'start' delays because only the content that has changed will be downloaded: the styles will be reused from your browser cache. The browser will request a refresh automatically the first time someone tries to access your page after the expiry date.
If the page is cachable, the internal CSS for this page is also cachable (as it is part of the page). But external stylesheets have the advantage that they can be used for many pages and are only requested once when cachable.
Therefor you first have an additional request (the external stylesheet) but then less data to transfer on further requests.
No, they will not. External CSS can be cached across multiple pages/requests, moreover you can typically compress these files using gzip.
Using external CSS ensures the look of all your pages is consistent, at least if you use 1 CSS file for the whole site. There may be a speed penalty for the first page, but from then on the CSS file is cached, and as a result subsequent pages will actually load faster.
I do occasionally use internal CSS where it's very specific to the page, and of no use elsewhere. Never place them in-line though; in-line CSS is very hard to maintain.

Resources