Whimsical.nu

FF: CSS Optimization Tips

A lot can be gained in terms of website performance by the wise use of cascading stylesheets and styles on the website, and these are relatively easy things to accomplish. They revolve around styles and stylesheet placement.

Stylesheets at the top

One important rule is placing stylesheets at the top, within the HEAD tags. While most browsers will load all styles eventually regardless of placement on the page, putting styles in the HEAD helps the page load progressively, giving users visual feedback that hey, something is loading. One of the worst things that could happen if your styles aren’t in the <head> tag is that the page does load–but there are no styles attached to your HTML elements, and then the page flickers to include the styles. It’s like going out without your clothes on, and then going back in to put them on.

Externalizing stylesheets

Styles can be included in the page source code itself in two ways: either within <style>...</style> tags, or within the style attribute of an HTML element. These are the “easiest” to do, however, it’s better if you put style rules in an external .css file, for a number of reasons:

  1. CSS files can be cached for users, and subsequent returns to your page serves the CSS from the user’s cache instead of asking your server for a copy for download. Your page file size is smaller since it doesn’t have style rules associated with it, and the external stylesheet itself isn’t downloaded on subsequent visits if it’s stored in the visitor’s cache.
  2. Other pages on your website can reuse this same external stylesheet. The optimization gains to this obviously means that all your pages will have a smaller size since there aren’t any styles on the source code itself. The development gains, however, are even better: one change in one file can update all your styles for your pages.

If your website uses a lot of inline styles, it may be quite a challenge to move them out to external stylesheets. It will usually mean a lot of editing and updating of files, the complexity of which depends on how fragmented your styles are.

Linking stylesheets instead of importing

There are two ways of including external stylesheets: via the use of the <link> tag, or @import. The former links your stylesheet to your page, and the latter imports one stylesheet into another. The two ways look like below:

<link href="styles.css" type="text/css">
<style type="text/css">@import url("styles.css");</style>

@import can be used to hide styles from earlier browsers, but in Internet Explorer, it behaves the same as using <link> at the bottom of the page–which pretty much negates the above best practices I’ve talked about.

CSS expressions are evil

Okay, so Internet Explorer is quirky. Sometimes CSS expressions seem to be the only way to fix it–I’ve seen a couple of IE fixes/hacks that require CSS expressions. They look similar to:

width:expression(document.body.clientWidth > 799? "800px": "auto" );

Unfortunately, they’re run pretty much every time the user interacts with the page: they’re run on page render, on browser resize, on page scroll, or even if the mouse moves over the page. If one needs to dynamically set styles, use JavaScript. If you really, really need to use an expression, use one that, in the end, overrides the style declaration so that it’s only run once.

IE filters are also evil

The most frequent use nowadays of IE CSS filters are to fix PNG images in Internet Explorer 6 via the AlphaImageLoader filter:

<div style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='pngimage.png',sizingMethod='scale');"></div>

However, this filter stops rendering and freezes the browser while the image is being downloaded, and since it’s done per element and not per image, each time this element shows up in the browser, you’ll get a bit of a freeze. It’s better to gracefully degrade to using PNG8 which works fine in IE6. If there’s no way out of using the AlphaImageLoader filter, user the underscore hack (_filter) or other IE6-only hacks to keep the style rule limited to IE6 users.

Good luck with optimizing your stylesheets! You can take a look at the other posts in this optimization series below:

  1. Website Optimization
  2. Minimizing HTTP Requests

2 Comments

FF: Minimizing HTTP Requests

As I mentioned last week, I’ll be talking about a few of my favorite techniques for making websites load faster–the rules and practices that I find interesting and intriguing as a web developer obsessed with a dash of challenge. ;)

One of the best ways to speed up website performance is by reducing the number of HTTP requests the website makes — it’s the first rule in YDN’s Best Practices for Speeding up your Web Site and YSlow, which is arranged according to what technique would have the most impact on your page’s performance. This rule can be quite tedious to do when optimizing a current website/layout, so the best case, really, is to start a project with this in mind.

The article explains it well, so I’ll just quote them (italics mine):

80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.

The use of CSS sprites has been around for quite a while now, and is the best way to reduce the number of HTTP requests to your server. A CSS sprite is basically multiple images combined into one single, larger image, which is then positioned into your HTML elements via CSS.

Can you imagine the conversation between the browser and the server for either case?

Browser: Give me the background for the Index menu item.
Server: Here you go, it will take around 1 second.
Browser: While I’m getting that, can you also get me the background for the Blog menu item?
Server: Here it is, another second for that.
Browser: And let’s not forget the background for the About menu item, too.
Server: Of course, here you go, you’ll get it in a second.

As opposed to when you use a CSS sprite for your menu items:

Browser: Give me the background image for the navigation menu items.
Server: Here you go, it will take a bit less than 2 seconds.

Short and sweet.

Note, however, that if your visitors are predominantly dialup users, this might not be a good rule for you to follow — mostly because you really can’t stuff any more data into that pipe than that pipe can handle. It will take longer for them to download the image, which will affect their perception of the website, as opposed to an image that gets downloaded faster and shows up on their browser faster. Remember those old-school rules about slicing header images? That’s basically rooted in that scenario: dialup can only download so much, so give them a couple parts of the header to download and see immediately. What’s best for your website depends on your target visitors.

There are a couple of CSS sprite tutorials and generators around:

…to name a few. If you’re just getting started with spriting, I’d suggest you create your sprite manually in your preferred image editing application before trying one of the generators and work on something simple like navigation or lists with icons for the first few times. This should give you a better grasp of what happens with a sprite.

Something to keep in mind: sprites will add complexity to maintaining your design. Adding another image to an existing sprite, updating your CSS code to reflect that (and possibly impacting current CSS rules on other images using that same sprite) is slightly more time-consuming than just uploading a new image and a new CSS rule to use that single image. And of course, the more images on a single sprite, the more difficult it is to keep that image and the accompanying CSS rules maintainable. One of the ways to combat this is to organize sprites according to use. As opposed to one über-sprite containing everything and the dust on the coffee table, a sprite for navigation and a sprite for list items separately is easier to maintain and organize.

Good luck with minimizing your HTTP requests!

2 Comments

Frontend Friday: Implementation focus on Indiscript’s lettered menu

For this week’s Frontend Friday I wanted to get a little more technical, and decided on focusing on and working though the implementation of Indiscript’s menus — the main navigation up top, and the script highlights on the sidebar:

What’s interesting about this implementation is that if I were to rename sections around, add new scripts to the sidebar, and otherwise need “new” menu items, I’ll never need to do anything more than just add the menu/link item, and every menu item or link presented this way makes use of just one 61.5kb image.

When I was working with the Indiscripts revamp, I knew I wanted something relatively simple, light, and easy to implement and extend for if/when I need to add new sections to the website. Usually that meant that artsy menu items were out…but I didn’t want to give up so easily. The result is the menu/link style you see now: an artsy letter serves as a background, usually in plain grey. The active menu item is green, and when you’re hovering over it, it becomes orange. If I wanted to use blue, pink, yellow, brown, etc–that’s all possible, with the help of CSS and PNG.

To make sure I have everything ready for if/when the time comes to add sections, I prepared a sprite image containing all the letters of the alphabet. For the uninitiated, a sprite (in terms of web development/CSS) is an image made up of several smaller images in measured distances from each other, in the interests of reducing HTTP requests and speed up website load times (see Website Performance’s What are CSS sprites?).

Read the rest of this entry »

2 Comments

Frontend Friday: Watch out for Divitis

Back when I first started using CSS, my favorite tag was undoubtedly the <div>. It was so versatile, and I did everything I could with that tag. It introduced me to absolute positioning and the CSS in general, and I’m forever grateful, but it also brought me away from the basics: HTML as a markup language. It’s also known as divitis: that is, having one too many <div> tags.

The result was code bloat, and once I started weaning away from this practice, I had hundreds of files to update, as they all looked like:

<div class="content">
<div class="title">Some heading!</div>
<div class="date">July 4, 2008</div>
<p>This is some of the content of the page. Yay!</p>
<div class="subtitle">Some subheading</div>
</div>

(I’m sure if you look hard enough you’ll find a couple of my older sites still sporting this sort of markup.)

Movements and events like the annual CSS Naked Day woke me (and hopefully a few others) to the sad truth that as web developers and designers, we can be so obsessive about needing every single pixel in place, but completely forget about keeping the house clean. The impact may be minimal at the onset (i.e., “hey, everyone sees the pretty decors after all!”) but just like your house after a rush cleaning because people are coming over tonight, you have to deal with guests stumbling into hidden mess, things not in the right place, and a painful cleanup job afterward.

(Of course, there’s the other end of the spectrum where holy wars are raged between the use of a <ul> and a <table> tag, which is just as bad, IMO.)

There are three things I do when working on a website to help me keep as close to “clean” as possible:

  1. Keep markup in the back of your mind when creating your design. The best example of this is creating a navigation menu. Can it be done in lists? What sort of arcane CSS-fu is needed to make it work like so?
  2. Start with a bare HTML page. I’m doing this right now for a couple of projects. I have wireframes (structures) where I’ve laid out roughly where things are going, but nothing else. No colors, no images, no JavaScript, just plain ol’ markup-py goodness.
  3. Once done, remove stylesheets and take a look. It’s easy for me to lose track of things when I’m on a roll, so this one personally has made me cringe a lot of times. Temporarily removing all styles from my work is a good way to see if it’s still readable and navigable even without all my pretty styles, and that it’s as close to how I designed it as possible. (This pretty much destroys all unordered lists masquerading as tables… so beware.)

Remember: there are 91 HTML tags available, one of which might serve the need and communicate your intent better. But don’t force it: sometimes saying nothing at all is better than being misunderstood.

1 Comment

Frontend Friday: Tools of the trade

I’m finally pushing through with an idea I’ve had for a while: Frontend Friday! Every Friday, I will be posting an entry about frontend development work, which includes topics on HTML, CSS, JavaScript, and basically anything related to the implementation of designs and UI on the web. These may be simple solutions you might know about, or weird experiments and topics that concern those who code layouts, whether done as a hobby or as part of work.

For the first Frontend Friday post, I’ve decided to write about a topic that’s rather central for all web developers: the tools that we use. We all use different programs and extensions and scripts to help us code up a nice layout for our websites. I wanted to share some of mine, and I hope you find them useful.

My top 7 tools:

  1. Aptana Studio

    I’ve been using Aptana well over a year now, and in fact I wrote a review about the web IDE before. Because it stems from Eclipse, and Java, it suffers a bit of lag especially when working with large files; I wouldn’t recommend using it for that quick 30-second style fix on your website.

    But working on websites that contains quite a few bells and whistles, I find Aptana to be quite helpful. The Project pane stores all ongoing projects, the Validation tab is quick to look up typos which result in syntax errors, the Outline pane makes jumping between functions and HTML nodes a breeze, and Code Suggest is always great to have around. (You should take a look at my review if you want to know more; while that was for the beta version, it’s still relevant.)

  2. Firefox

    Yes, Firefox just had to be there. I will admit that as of late I’d been very frustrated with Firefox’s memory-hogging practices and annoying lag, and if it weren’t for Firefox being insanely great for web development, I might have dropped it for the faster Safari. Firefox is a great standards-compliant browser, plus it provides an avenue for a plethora of web-developer-friendly tools, some of which are…

  3. Web Developer Toolbar

    Chris Pederick’s Web Developer Toolbar is impossible to live without. It’s lightweight and contains a lot of helpful tools: disabling cache to make sure you see your CSS updates, cookie manipulation, CSS lookups, markup and style tools for debugging, browser resizer, viewing generated source (for all those whizzy JS things), and more. If you’re a developer and you don’t have this on Firefox yet… what cave have you been living in?!

  4. Firebug

    Actually, Firebug vied with the Web Developer Toolbar for the “must have” spot, with the toolbar winning simply because it’s lighter and more mainstream: even if you’re a hobbyist making personal websites during your free time, the toolbar is useful. Firebug is also a must-have, but mainly for more heavy duty stuff, and especially for debugging purposes: completely clueless what styles are messing things up on a certain element? Lost as to what is happening to your variables when running JS? Firebug makes digging into code easy. I can’t count the number of times Firebug has saved me hours of trawling through CSS or numerous alert() calls.

  5. Multiple Internet Explorer installations

    There are numerous multiple IE tools out there, but the one I personally use on my Windows test machine is TredoSoft’s Multiple IE. I really only test for IE6 and IE7, though (I should install IE8 soon, too…). It’s a bit of a pain, but that’s the way life rolls. The IE Developer Toolbar is also a must-have for IE-proofing your website. I hope they update the toolbar to include a debugger soon.

    Naturally, you will also need other browsers installed, according to what you wish to test with. I test according to Yahoo!’s list of A-grade browsers, even for my personal work (well, in varying degrees, as I don’t have multiple images of Windows sitting in my personal machine, for instance).

  6. YSlow

    YSlow analyzes my pages’ load times. I typically only use this nearer to the end of development, to check if I need to combine more images into sprites, chunk together CSS and JS, etc. It’s definitely a good guideline checker for webdev best practices, which may or may not be critical for you, depending on what you are working on.

    YSlow takes into consideration Yahoo!’s rules for high performance websites, which every web geek into making websites should read through at least once.

  7. Fiddler and/or Tamper Data

    These two are mostly useful for deeper digging into the communication between your website and the server, and may or may not be applicable for the type of work you do. I find it highly useful for verifying form submissions’ raw data and AJAX requests — you can stop the data transmission, fudge up the content, and release it, which helps you trap bugs and issues.

    Tamper Data is a nifty Firefox extension for this purpose, and Fiddler is an HTTP debugger tool, much more robust than Tamper Data. Unfortunately, Fiddler is not available on Mac OSX — I’ve been looking for a good alternative for a while now (Paros looks like an interesting alternative, but for some reason I can’t get it to start monitoring traffic).

So those are the top 7 tools I use for working with code. What are yours?

4 Comments

Heading Tags

A while back, maybe three years back and from the time I started using CSS, I used to do a couple of markup quirks (that incidentally made it easier to spot copycats, but that’s another story). I used CSS classes all over the place, like below:

<div class="content">
<div class="divTitle">Some title</div>
<div class="divSubTitle">Some sub heading</div>
<p>My content went here, in ordinary P tags.</p>
</div>

It worked for me. But starting from around two years back, I finally weaned myself off of using the semantically-blank DIV tags (where appropriate) and use proper HTML markup. My biggest reason for this is lesser code, and my page is “prettier” when the CSS is turned off. Observe:

<div id="content">
<h1>Some title</h1>
<h2>Some sub heading</h2>
<p>My content went here, in still ordinary P tags.</p>
</div>

In terms of style control, it was easily done via CSS anyway; and if I wanted a completely blank stylesheet anyway, a nice CSS reset will do that for me. (A word of note though: CSS reset does have its pros and cons. Personally I’m still a bit on the fence as to whether I’d go for using one that reset all the native styles or not, above the paddings and margins.)

An interesting post on heading tags, including a possible system/technique on using them, was posted by Matt Snider: When to Use Heading Tags. It’s a good, interesting read.

6 Comments