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

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!

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.

Combining CSS files: per site or per page template?

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

serve required styles only CSS

Is there a way of filtering large CSS files for the only required selectors on a page, and creating css files that contain just these selectors?
Case: I have a very large CSS file that I want to filter on a per page basis, so that the file size is cut down and can be cached by mobile devices. I was thinking along the lines of something like a server side dust me selectors tool.
The particular project I am working on is using ASP.NET MVC.
Thanks
Heads up that while you might get smaller individual page loads, the overall load of browsing the site will be higher given that you're hitting the server each and every time for a new CSS file (rather than just caching a site-level CSS file once).
In addition, if you find that there are a lot of unique per-page CSS declarations, the CSS for the site may not be written very well. So the solution may be to go back and rethink the CSS structure to begin with, perhaps looking into OOCSS models:
http://wiki.github.com/stubbornella/oocss/
Unfortunately, none of that answers your specific question.

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.

Managing CSS on large websites

I've recently begun working on a very large, high traffic website. We would very much like to reduce the size and number of our style sheets, minification is one route we will pursue but is anyone aware of any tools for checking ID and class use? Literally scanning the website to see what's active and what isn't?
Alternatively any software for redacting the css to reduce repition and size?
Thanks in advance
Literally scanning the website to see
what's active and what isn't?
Dust-Me Selectors is a Firefox plugin that you can use to show what css rules aren't being used.
http://www.sitepoint.com/dustmeselectors/
I can certainly recommend Page Speed (http://code.google.com/speed/page-speed/) by Google to check the performance (and possible improvements) of your webpages.
Page Speed also checks CSS and usage of classes on your webpages.
It is used in combination with Firebug.
Gzip compression in the webserver.
Expiry dates that lie far in the future to avoid redownloading the CSS files.
Alternatively any software for
redacting the css to reduce repition
and size?
Yet another level of indirection ... You (and your team) should write long CSS files with as many comments as needed and then write a tool that will publish merged files as needed (different templates need different files), stripped comments and minified as http://www.cleancss.com could do (CSSTidy). Readability comes first if you wan't to be able to modify a file in 1 month or keep track of modifications (or worse if sb else must do that!).
Other options are to reduce the number of templates used throughout the site. No need of two templates with 2px differences (grid layouts are a good way to stick to this) or inconsistent ways of displaying error messages. Define a common look and feel to your site and give instructions to webdesigners, if it isn't already done.

Resources