Combining CSS files: per site or per page template? - css

We all know that we're supposed to combine our CSS into one file, but per site or per page? I've found pro's and cons to both.
Here's the scenario:
Large site
CSS files broken out into one file for global styles and many for modules
Solution A: Combine ALL the CSS files for the whole site into one file:
Best part is that the one file would be cached on every page after the initial hit! The downside is that naming convention for your selectors (classes and id's) becomes more important as the chance for a namespace collision increases. You also need a system for styling the same module differently on separate pages. This leads to extra selectors in your CSS which is more work for the browser. This can cause problems on mobile devices like the iPad that don't have as much memory and processing power. If you're using media queries for responsive design, you're troubles compound even further as you add in the extra styles.
Solution B: Combine one CSS file per page template:
(By page template I mean one layout, but many different pages, like an article page)
In this scenario, you lose most of the issues with selecting described above, but you also lose some of the cache advantages. The worst part of this technique is that if you have the same styles on 2 different page templates then they'll be download twice, once for each page! For instance, this would happen with all your global files. :(
Summary:
So, as is common in programming, neither solution is perfect, but if anyone has run into this and found an answer I'd love to hear it! Especially, if you know of any techniques that help with the selector issue of Solution A.

Of course, combine and minify all the global styles, like your site template, typography, forms, etc. I would also consider combining the most important and most frequently used module styles into the global stylesheet, certainly the ones that you plan to use on the home page or entry point.
Solution B isn't a good one: the user ends up downloading the same content for each unique layout/page when you could have just loaded parts of it from the last page's cache. There is no advantage whatsoever to this method.
For the rest, I would leave them separate (and minified) and just load them individually as needed. You can use any of the preloading techniques described on the Yahoo! Developer network's "Best Practices for Speeding Up Your Web Site" guide to load the user's cache beforehand:
Preload Components
By preloading components you can take advantage
of the time the browser is idle and request components (like images,
styles and scripts) you'll need in the future. This way when the user
visits the next page, you could have most of the components already in
the cache and your page will load much faster for the user. There are actually several types of preloading:
Unconditional preload - as soon as onload fires, you go ahead and fetch some extra components. Check google.com for an example of how a
sprite image is requested onload. This sprite image is not needed on
the google.com homepage, but it is needed on the consecutive search
result page.
Conditional preload - based on a user action you make an educated guess where the user is headed next and preload accordingly. On
search.yahoo.com you can see how some extra components are requested
after you start typing in the input box.
As far as the conflicting selectors go: combining all the files and doing it any other way should not make a difference, this is a problem with your design. If possible, have all modules "namespaced" somehow, perhaps by using a common prefix for classes specific to the module, like blog-header or storefront-title. There is a concept called "Object-oriented CSS" that might reduce the need for lots of redundant CSS and module-specific class names, but this is normally done during the design phase, not something you can "tack on" to an existing project.
Less HTTP requests is better, but you have to take file size into consideration as well as user behavior and activity. The initial download time of the entry page is the most important thing, so you don't want to bog it down with stuff you won't use until later. If you really want to crunch the numbers, try a few different things and profile your site with Firebug or Chrome's developer tools.

i think you can make global.css that store style that need every template.
And you could make css in each template.
Or simply use css framework like lescss

Related

What does removing unused css mean in google audit?

I am using google's audit and its tells me to remove unused CSS. I don't know if that css is for just that page or the whole site. The CSS might be there but not needed on that page but another page. Can someone tell me how this works?
It is telling you to remove unneeded CSS for that page.
However you have rightly pointed out the flaw in this suggestion as it only takes into account the current page (in it's initial state, obviously if you have a pop-out menu it won't gather the CSS for that).
Think of it more as a guideline of making sure you don't send the whole of Bootstrap just for the grid and column layouts for example.
Overall this is very difficult to fix, just use the coverage section on the performance tab in Developer tools to make sure you don't have any massively bloated CSS files and you will be fine.
Obviously reduce your unused CSS if it is easy to do so.
The only other thing that this point covers (in it's description, not as part of it's monitoring) is deferring non-essential CSS.
You should defer any Style Sheets that are not required for rendering 'above the fold' content (and inline your 'above the fold' CSS).
This point is also covered in 'Eliminate Render Blocking Resources' so I never quite get why they add the suggestion under this part as well but I have added it for completeness.
I find this rule was good at guiding me when designing a theme from the ground up as it made me seperate global CSS and page CSS more effectively.
Unless your site is scoring 98 / 100 (or you have hundreds of kilobytes of CSS) and you want to squeeze that last little bit of performance out of the site, simply minify and combine your CSS files and ignore this point.
Google's audit tool compares the entire stylesheet against the current URL and then tells you how much of it is actually not used by the browser.
The browser however still needs to download the entire file and then match all CSS selectors that apply to the current URL.
There are many ways to deal with this, but I find it the easiest to use an external API tool like Splitcss that does this for you on URL basis.
If you have only a few URL patterns in your web application, you can use some CLI tools like purgecss or uncss.

CSS speed optimisation - Why multiple files are better then only one?

Less HTTP request the better it's, right ?
Regarding to Google best practice explanation, less unused css rules is also better.
The browser's CSS engine has to evaluate every rule contained in the file to see if the rule applies to the current page.
Even if a stylesheet is in an external file that is cached, rendering is blocked until the browser loads the stylesheet from disk.
In your opinion what's giving better performance :
One css file per page.
One general css that will be cached (even if there will be +70% unused css / but avoiding any other http requests).
Google speed best-practice
One of the important sentence to note from the Google best practice document is "Often, many web sites reuse the same external CSS file for all of their pages, even if many of the rules defined in it don't apply to the current page".
This needs to be taken into account as if the css file has additional code that is never going to be used if user does not visit the page for which this redundant code applies then we are certainly wasting the bandwidth which may not be a proper trade off for an additional HTTP request.
This leads to additional time to load the file plus the time wasted in evaluation of that redundant code.
Certainly using multiple files for just a single page (like different header/footer css files) would be a bad practice.
And as you know that there is not a perfect solution for any problem. You have to choose the best thing that suits your need.
So, I would say the decision to use multiple files or a single file is solely based on the overall structure of website and other trade offs.
Loading CSS is usually extremely quick. CSS blocking is something you will probably never catch. Whereas JavaScript could do so that you are visually aware that it's being downloaded. (white spaces while rendering the page).
In reality one CSS is good enough, because of a single HTTP request.
Optimization should go towards JavaScript, because this is where you can see the page slowing down. We are talking about a second-two of a difference or less here.
Here is a site where you can enter URL and it will check load times. In the graph below you can compare CSS load times.

How can I effectively clean up styles in a large web site?

Our web site has been under a constant development for a better part of the last five years. As it happens, pretty much all the styles for the site are in one big CSS file. With time this css file has grown to about 9,000 lines - and I'm sure some of those styles are not used any more and quite a few styles provide duplicate functionality.
The site is written with PHP/Smarty; there are over 300 smarty templates and the whole site contains over 1000 different pages (read - unique URLs). I'm sure it will continue growing - as will the CSS file.
What's the best way to clean up this file?
Update: Unfortunately, online parsers where I put in a URL won't work for me, as 75% of the site is behind username/password logins - and depending on login, there are half a dozen different roles, each of which has their own set of of pages. There are also transactional elements (online shop), where the pages are displayed after (for example) credit card payment is taken/processed. I doubt that any online tool would be able to handle any of these. Therefore if there's a tool, it would have to work on a source tree.
Short of going through each .tpl file and searching the file for the selectors manually, I don't see any other way.
You could of course use Dust-Me selectors, but you'd still have to go through each page that uses the .tpl files (not each url as I know that many of them will be duplicates).
Sounds like a big job! I had to do it once before and I did exactly that, took me a week.
Another tool is a Firebug plugin called CSS Usage. As far as I read it can work across multiple pages but might break if used site-wide. Give it a go.
Triumph! Check out the Unused CSS online tool. Type your index url into the field and voila, a few minutees later a list of all the used selectors :) I know you want the unused ones, but then the only work is finding the unused ones in the file (ctrl+f) and removing them :)
Make sure to use the 2nd option, they'll email you the results of the crawl of your entire webpage. Might take up to half an hour, but that's far better than a week. Take some coffee :)
Just tested it, works a treat :)
I had to do this about 3 years ago on a rather large classic ASP web application.
I took the approach that there are only a finite number of styled items on each page and started by identifying these. For example, I went through the main pages and identified that the majority of labels were bold and dark blue and that all buttons are the same width (for example).
Once I'd done that, I spoke to the team and we decided that anything that didn't conform to these rules I'd identified should conform, so I wrote a stylesheet based on this assumption.
We ended up with about 30 styles to apply to several hundred pages. Several regular-expression-find-and-replaces later (we were fortunate that the original development had used reasonably well structured HTML) we had something usable that just needed the odd tweaking.
The key points are:
Aim for uniformity across the site. In other words, don't assume that the resultant site will look exactly the same as the original, but aim for it to look the same as itself (uniform) from page to page
Tackle the obvious styles first (labels / buttons / paragraph fonts / headers) and then worry about the smaller styles or the unique styles later
You might also find that keeping unique styles (e.g. a dashboard page that has unique elements that don't appear elsewhere) in separate files to keep the size of the file down. Obviously, it depends on your site as to whether this would help.
Additionally, there are many sites that will search for these for you. Like this one: http://unused-css.com/ I don't know how they measure up to Dust-Me Selectors, but I know that Dust-Me selectors isn't compatible with Firefox 8.0.
You could use Dust-Me Selectors plugin for FireFox to find unused styles:
http://www.sitepoint.com/dustmeselectors/
If you have a sitemap you could use that to let the plugin crawl your site:
The spider dialog has all the controls for performing a site-wide spider operation. Enter the URL of either a Sitemap XML file, or an HTML sitemap, and the program will read that file and extract all its links. It will then load each of those pages in turn and perform a cumulative Find operation on each one.
I see there's not a good answer yet. I have tried the "Unused CSS online tool" and seems to work ok for public sites. The problem is if you have a CSS to show your public website + an intranet (for example: wordpress site + login for registered users). The intranet pages woun't be tracked and you will lose your css styles.
My next try will be using gulp + uncss:
https://github.com/ben-eb/gulp-uncss
You have to define all the urls of your site (external and internal) and (maybe; not sure) if you are running the site with user + password on your browser, gulp+uncss can go inside the internal url's.
Update: I see unused-css online tool has a login solution!

Is Creating Separate CSS Files Per Page To Speed Up Load Time Overkill?

I've been using Google PageSpeed to improve my site's performance. One of its recommendations is eliminating unused CSS in my app. Although a lot of the CSS is unused for a given page, it is used elsehwere in the app.
What's the right approach here? I'm considering creating a base CSS file for common CSS and then separate files for each individual page. Luckily there aren't that many pages. Is this overkill? And is there a better approach?
This is a Rails app, and I'm using asset_packager to minify my CSS and Javascript
Thanks!
Moe
It won't speed up your application because you will be adding new http requests, while if you pack all CSS into one file, that file will stay in the cache and you won't have to have an http-request for it for subsequent pages.
Google PageSpeed simply mean that you shouldn't provide styles you don't use anywhere in your application or only in pages that a user can't visit, for example the admin area.
As people in here mentioned, definitely not. You will just add new http requests. You should really keep in mind that pagespeed will probably always show that you have unused css on a given page, but that's not really a big issue.
Take a look at the other recommandations page speed is showing like enabling compression, optimizing the images (consider using css sprites if you aren't already) and more.
See also yahoo best practices to speed up your site.
That'll depend on the size of the file(s) and the way people use your site. If the file isn't huge to begin with and people will often go to many different pages, having page-specific css files will forfeit the benefit of caching, which is generally going to garner more benefit.
The overhead of an extra HTTP request to download yet another CSS file greatly outweighs the overhead of an extra few KB in the master CSS file.
I think it is best to componentise your stylesheets. For example, you might have a base css that provides the layout for your pages. Then you might have a theme css that provides colours, images, borders - visual elements. Then you might have separate css files for individual UI components, e.g. popup.css, calendar.css etc.
base.css
theme-blue.css
theme-blue-popup.css
theme-blue-calendar.css
This approach makes it easier to manage your styles (and switch them if you need to). More relevant to your question however, is that you now have the ability to specify what stylesheets are needed for each page on your site. Now if the user visits the homepage of your site only, and the homepage has no popups or calendars, then they haven't downloaded the styles for the components they aren't using. As they proceed further into the site, they will get the required stylesheets as and when they need them.

Which combining css technique?

Which of the following would you say is the best way to go when combining files for CSS:
Say I have a master.css file that is used across all pages on my website (page1.aspx, page2.aspx)
Page1.aspx - A specific page that has some unique css that is only ever used on that page, so I create a page1.css and it also uses another css grids.css
Page2.aspx - Another specific page that is different from all other pages on the site and is different to page1.aspx, I'll name this page2.aspx and make a page2.css this doesn't use grids.css
So would you combine the scripts as:
Option1:
Combine scripts
csshandler.axd?d=master.css,page1.css,grids.css
when visiting page1
Combine
scripts
csshandler.axd?d=master.css,page2.css
when visiting page2
Benefits: Page specific, rendering quicker since only selectors for that page need to be matched up no unused selectors
Drawback: Multiple combinations of master.css + page specific hence master.css has to be downloaded for each page
Option2:
Combine all scripts whether a page needs them or not
csshandler.axd?d=master.css,page1.css,page2.css,grids.css
(master, page1 and page2)
that way it gets cached as one. The problem is that rendering maybe slower since it will have to try and match EVERY selector in the css with selectors on the page even the missing ones, so in the case of page2.aspx that doesn't use grids.css the selectors in grids.css will need to be parsed to see if they are in page2 which means rendering will be slow
Benefits: One file will ever be downloaded and cached doesn't matter what page you visit
Drawback: Unused selectors will need to be parsed by the browser slower rendering
Option3:
Leave the master file on it's own and only combine other scripts (the benefit of this is because master is used across all pages there is a chance that this is cached so doesn't need to keep on downloading
csshandler.axd?d=Master.css
csshandler.axd?d=page1.css,grids.css
Benefits: master.css file can be cached doesn't matter what page you visit. Not many unused selectors as page spefic is applied
Drawback: Initially minimum of 2 HTTP request will have to be made
What do you guys think?
Cheers
DotnetShadow
Personally I would say Option 2 - Combine All Scripts. As your website grows, the number of pages will increase, and tracking which CSS files go with which files will become unmanageable. You might think some CSS is only used on one page, but I bet in the future that won't be true.
Once the user has visited one page, they will have all CSS and the other pages will be vastly quicker. (Although you might want to optimize your homepage separately). Think web application, not web page.
Have you measured the page loading time with Firebug or something similar? I'm asking because I'm curious wether it will make a big difference at all.
Anyway, I just wanted to point you to a CSS Framework developed by yahoo. They've got a very clean structure, and maybe you want to design your own framework in a similar way. They use a reset CSS File to create the same preconditions for every browser, which I find a clever thing to do.
YUI 2: Grids CSS
Maybe it helps.

Resources