Monday, August 11, 2008

When do browsers download images defined in Cascading Style Sheets?

Just the other day I was talking with a coworker about ASP.NET Themes. We were addressing a question about putting multiple Cascading Style Sheets (CSS) into a theme.

Unless you do something special, ASP.NET Themes adds a link reference to every CSS file in the theme directory. We were fine with this behavior even if the styles weren't used by the page, but what about all the background images defined in the style sheets?

Here's where we asked the question "When do browsers download images defined in Cascading Style Sheets?"

Here are my findings:

Both Internet Explorer 7 and FireFox 3.0 do not download an image unless the style is used on an element of the page.

For Example:

Consider a style sheet called style.css which containes

.image
{
 background:transparent url(testImage.png);
}

If you have a html file which contains:

<html>
    <head>
        <link type="text/css" rel="stylesheet" media="screen, projection" href="style.css">
    </head>
    <body>
        <p>Hello World</p>
    </body>
</html>

There will be two requests to the server: html, and css

If you have a html file which contains:

<html>
    <head>
        <link type="text/css" rel="stylesheet" media="screen, projection" href="style.css">
    </head>
    <body class="image">
        <p>Hello World</p>
    </body>
</html>

There will be three requests to the server: html, css, and png

I tested using FireFox 3.0 with FireBug (HEH HEH, FIRE!), and Internet Explorer 7 and Fiddler.

1 comment:

  1. Your analysis is spot on! Hey, did some rogue .NET developer figure out how to avoid having all the CSS sheets included? :)

    ReplyDelete