High Performance CSS code design
In the last few years much emphasis has been placed on web performance issues. Browser vendors have optimized JavaScript engines, JavaScript libraries have been honed, and content delivery has been improved. Unfortunately, CSS has received less attention. Developers have been advised how to optimally transfer CSS files, and instructed to use CSS shorthand, but very little has targeted CSS code itself.
Ms. Nicole Sullivan is among those looking to improve CSS code. She has been promoting “OOCSS,” or “Object Oriented CSS,” her methodology for how to design and refactor CSS 1. She has collected a number of best practices for architecting a CSS framework. The benefits are simple: CSS will perform better, become more modular, as well as being grounded with a consistent API, making it easier to learn and use. This is accomplished by reducing the file size and complexity of our CSS.
While many of these techniques can be considered common practice for experienced CSS programmers, implementing them can be difficult. The art is in analyzing trade-offs and picking the optimal path. That said, these rules are not for everyone, or every site. It all boils down to deciding if the site’s performance gain is greater than the time it takes to learn and use the techniques.
Useful for sites with
- Many pages
- A common visual and structural design
- Critical performance requirements
Less useful for sites with
- A few pages or just one page
- Varying design (possibly “portfolio” or design sites)
- Few performance concerns
So how do we get started? We go hunting for bad code smells. In Chapter 3 of Refactoring: Improving the Design of Existing Code, Martin Fowler and Kent Beck coin the phrase “code smell,” meaning “structures in the code that suggest the possibility of refactoring.” Simply put, we go looking for chunks of code that our intuition tells us could be cleaned. In the chapter heading, Grandma Beck is quoted (then talking about child-rearing), “If it stinks, change it.” We’ll take a more formal approach to finding these code smells, going from easy to difficult. First, we’ll sniff around the CSS selectors, and then move onto the CSS properties. Finally we’ll look for visual design patterns that can direct the structure of our CSS.
Selectors
Selectors are both the easiest place to find code smells in CSS and the easiest to correct. Three big code smells tend to stink up CSS selectors; unused selectors, location-based selectors, and overly specific selectors. Each contributes significantly to increased CSS file size.
Continue reading