FF: CSS Optimization Tips

Entry posted on 2008-09-12 1:00 pm

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

FF: Minimizing HTTP Requests

Entry posted on 2008-09-05 12:00 pm

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!

FF: Website optimization

Entry posted on 2008-08-29 12:00 pm

One of the things I’ve realized when I started working for Yahoo! is the importance and “interesting-ness” of website performance optimization. In an industry where things can get repetitive (how many <p> tags can you code in one day?), the challenges brought about by ensuring a website is properly optimized in terms of performance and page load is welcome and quite engrossing.

With high-speed Internet, a lot of times we tend to forget about the size of the files we put up on the Internet on our websites, much less worry about how long someone takes to load our website. It’s easy to forget, but when you’re on a crappy dialup or using your mobile phone as a model (er, like me while transitioning houses!), or you’re, say, a trouble-checker for one of the fanlisting networks out there, the wait for websites to load can take its toll, and feel painful on the pocket.

Two reasons why optimizing websites — even if you’re not Yahoo! — are:

  1. You keep visitors longer, because the wait time is less, and people like things faster than you can chug them out. It’s all about instant gratification these days.
  2. You save on bandwidth! Something smaller by even 10kb can mean megs or gigs of bandwidth savings in the long run. If you pay for hosting and you have a fairly popular website, this is a big deal.

A lot of this work is done on the frontend side of things. After all, once the server has cobbled together the page, the bulk of serving the page code and objects rely on the user’s connection. The HTML code is just one part of what’s served out to people, but images, stylesheets and other media are downloaded all after the source is available. And these are the things that users see and perceive. The image below shows around a third of Firebug’s Network tab on one of my websites:

Building and serving out the page takes up only 715ms. But the rest of the objects on the page are then loaded, and I end up with a 4.08-second load time. That isn’t so bad, but all the rest of the objects on that page form the bulk of the load time that users have to endure. If we save a few milliseconds from each object, overall we can get a snappier load time for the whole page.

In The Psychology of Web Performance, Andrew King highlight a few interesting results of bloated load times, in case you’re still not convinced:

  • Google found that moving from a 10-result page loading in 0.4 seconds to a 30-result page loading in 0.9 seconds decreased traffic and ad revenues by 20% (Linden 2006).

  • Tests at Amazon revealed similar results: every 100 MS increase in load time of Amazon.com decreased sales by 1% (Kohavi and Longbotham 2007).

Over the next Frontend Fridays, I’ll talk a little more about some ways to optimize frontend performance. I’ll mostly be going through the rules Yahoo! has published, but I will probably cherry-pick and talk about the ones I like most, the ones I like doing. Stay tuned :)

FF: Another look at skinning websites

Entry posted on 2008-08-22 12:00 pm

I’ve always liked themes and website skins, the type where visitors can change the look of a website using a switcher. I even made a script for it. I think they’re a fabulous tool for making a website interactive, and giving users the power of choosing how they want to experience the website in question. This is most useful and prevalent in forums and boards, where users are many and varied: some prefer reading in dark environments, and some prefer lighter ones.

But of late I’ve been thinking that theming and skinning websites isn’t all that great, especially viewed in certain conditions. To clarify: I’m talking about a theme or skin being more than a color-only difference between themes/skins.

I realized that one of the drawbacks for me is the false sense of “interactivity” in the website. Understand, the websites I’ve skinned are all smallish fansites and fanlistings, containing minimal updates. Skinning has become one of the most popular “interactive” features of a fanlisting. Unfortunately, it’s lulled me into feeling that it’s “enough”. Which is a bad place to be for anyone who owns a website. More content and other forms of interactivity should be the focus; there are plenty of other ways to do that.

It’s lulled me into keeping old layouts around. I’m ashamed to say a couple of them are half-assed layouts that are there because the more skins there are, the nicer the website is! And, why skin a website when you only have two skins? So keep them all and give the users choice. Uhm, wrong tactic there. Skin retirement should be done semi-regularly, to keep layouts fresh and up-to-date.

I also can’t help but feel that there has to be some brand dilution there somewhere, unless skinning is carefully managed, of course. You have a subset of users using one skin, another subset using another, and unless these skins are quite similar (like the really nifty Day/Night skins I’ve seen crop up recently) the users of skin 1 will tend to approach the website differently from users of skin 2. Websites who’ll have these problems will probably be few and far between, but I can’t help but feel that this is a valid concern.

I certainly feel that skinning is one aspect of website interactivity that one should take a look at when planning a website, but shouldn’t be taken lightly. It adds a bit more complexity to managing the website and the users of the website, but when done well, it’s a fun feature for visitors. I still can’t get over the Day/Night skins some websites use; if it would work for one of my websites, I’m soooo there! ;)

But for now, I’m steering clear of skinning until I’ve real reason to use it.

Frontend Friday: Too much AJAX

Entry posted on 2008-08-08 2:00 pm

Alex asked in last week’s Frontend Friday:

I just wanted to know how you decide how much AJAX is too much AJAX? You don’t seem to use much (if any) on this website.

It’s a good question, but the answer isn’t too straightforward: it will always depend on a large number of factors. For me, an indication of a developer/team getting too AJAX-happy would be when the site becomes unusable when JavaScript is turned off or isn’t working. For example,

  1. a website that loads all (or most) of its content via AJAX, therefore rendering the page content-less without JavaScript; or
  2. a website whose navigation is inaccessible without JavaScript.

JavaScript should enhance websites and applications, no doubt about that. Most, if not all, of the well-loved web apps of today are due to the snazzy-ness of AJAX. But we can’t always rely on JavaScript being present: even if users have it turned on, spotty connections and unexpected data returns can result in JavaScript being pretty much nonexistent. Progressive enhancement and/or graceful degradation should be important when working with JavaScript–whether or not you’re doing asynchronous calls or not.

However, like I said, the answer isn’t straightforward. Some applications really do rely on the existence of JavaScript, and for good reasons. Graceful degradation can be prohibitively difficult when you’re dealing with some specialized web applications, like mail: Yahoo! Mail and GMail come to mind. User interactions with both of these are so fine-tuned and uses a lot of convoluted interlocking parts, and degrading gracefully would be a pain. That’s why both apps have a no-JavaScript version as well (Mail Classic and Basic HTML view, respectively).

As for the second part of the question–no, Indiscripts doesn’t use any AJAX :) Mostly because I don’t see a need for it, or the “need” to use AJAX is lower than the time I have budgeted for designing and coding up my tech blog ;)

More entries