mattstuehler
mattstuehler

Reputation: 9282

If you have CSS that's specific to that page, is it better to include it in the <head> or a separate file?

I'm working on a web app; one of the screens requires some CSS that's very specific to that page (i.e., it isn't used anywhere else in the app/site).

So - I have three options:

  1. Include it in the global CSS file
  2. Include it in a page-specific CSS file
  3. Include it in the <head> of the page

The downside of option 1 is that the CSS will be loaded when when the user visits any screen of the app, even if she never visits this specific screen (which is quite likely).

The downside of option 2 is that it's a separate HTTP request; since the CSS itself is trivially small (<1kb) - it seems like the overhead of the http request itself is worse than the actual bandwidth to download the data.

The downside of option 3 is that the user will download the CSS every time she visits the page (i.e., the CSS won't get cached). But since this is an infrequently viewed page (and seldomly revisited page), this seems minor.

To me - it seems like option 3 might be the best. But everything I read seems to discourage that approach.

Given how hard experts push CSS sprites to minimize http requests, doesn't the same logic apply to a tiny CSS file? So, why isn't #3 a good option? Are there other considerations I've missed?

For what it's worth - it seems like this same question applies to any page-specific JavaScript; I could include that in a <script> tag at the end of the page, or in a separate .js file.

Thanks in advance.

Upvotes: 1

Views: 107

Answers (2)

Jules
Jules

Reputation: 14510

If you're using it in a single page, you'd best include it in the <head> directly. It results in fewer HTTP requests going through, less bandwidth usage, and marginally faster loading.

You can also consider using a combination of an internal and external stylesheet: for stuff that you might use site-wide, like the styles for h1, h2, h3, and so on, link to an external stylesheet. For stuff specific to the one page, like the background-image, put style in the <head>.

Upvotes: 1

Alex
Alex

Reputation: 2420

Put it in the head and move on to other problems. :)

"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%." --Donald Knuth

Upvotes: 1

Related Questions