Which should be included first in <head>?

Hi,

At the place I work, I was asked a simple but interesting question: Which should be linked to first in the HTML <head>: CSS or Javascript? And why?

The first thought that came to me was CSS. Because CSS defines the structure of the page and the structure should be loaded first before other elements begin to work. And the elements inside HEAD are called as they appear…

What do you think is the correct answer?

CSS should be loaded first then JS for the simple reason that I would rather my visitors see a styled non interactive page first, then get the interactive part after the css has loaded.

By the way: Most JS should be loaded at the bottom of the page (unless of course it needs to be in the head), it speeds up page load times considerably.

Typically, in the head, I include all the text-based tags first (title, meta, etc), then the favicon, then CSS, then JS. Essentially, the order boils down to what is necessary first to get the page to display or what loads faster first to get the page to display.

However, there are other schools of thought that JS should be placed at the end of the document before the </body> tag to help display the page faster in the browser. Anything in the head must be downloaded first before proceeding further down into the HTML, so there would be a delay in displaying the HTML while everything in the head is being downloaded. Then there is also the processing time of the JS itself once the file/code is downloaded. JS isn’t often completely necessary for a webpage to function in its first few moments of life in a browser.

On top of that, CSS, JS, and image files that need to be downloaded can be placed on different subdomains, which then allows for simultaneous downloading. But–that has to be balanced between the amount of time it takes to actually do a DNS lookup versus the download time or filesize of the file being downloaded.

If you use http-equiv meta tags, especially with the Content-Type attribute, be sure to add the before anything else (including the title) in the document. This increases rendering speed, because any content rendered before that has to be re-rendered by the browser.

I would place the title immediately after. If the user opens your link in a new tab or window, the title will display in that tab or window title in stead of the URL, indicating that the site is downloading.

After this, I place the style sheets. I don’t use Javascript if I can avoid it, so this is usually a moot point for me.

If your design use a lot of small icons and other graphics, you should seriously consider using sprites. This will significantly reduce download time, as the number of HTTP queries is reduced drastically. For small icons, the HTTP header can exceed the size of the actual image, so this is something to look into.

It also often helps to manually call a script function right before </body> instead of waiting for onload if you’re making layout or content changes. It will get applied BEFORE the page is rendered instead of after.

I don’t even use onload anymore – it happens “too late” in the chain of events for my use.

The order of things in the head doesn’t “really” matter, but I like to do META->SCRIPT->LINK->TITLE…

Using the above mentioned technique my scripts make their changes before rendering even happens anyways, so the order on that doesn’t matter.

You SHOULD take care with certain meta’s… Meta’s that define how the content should be accessed should come before meta’s that dont’ actually render or effect page use. That’s why my usual header reads:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
	xmlns="http://www.w3.org/1999/xhtml"
	lang="',$settings['language'],'"
	xml:lang="',$settings['language'],'"
><head>

<meta
	http-equiv="Content-Type"
	content="text/html; charset=',$settings['encoding'],'"
/>

<meta
	http-equiv="Content-Language"
	content="',$settings['language'],'"
/>

<link
	type="text/css"
	rel="stylesheet"
	href="',$settings['themeDir'],'screen.css"
	media="screen,projection,tv"
/>

<!--
	Don't forget to implement these later!

<link
	type="text/css"
	rel="stylesheet"
	href="',$settings['themeDir'],'print.css"
	media="print"
/>

<link
	type="text/css"
	rel="stylesheet"
	href="',$settings['themeDir'],'handheld.css"
	media="handheld"
/>

-->

<title>
	',(
		isset($pageTitle) ? '.$pageTitle.' - ' : ''
	),$siteTitle,'
</title>

</head><body>

Since character encoding and language should be specified ASAP before anything else… Especially character encoding (not that it’s obeyed in most cases with the http header typically overriding it)

– edit – excuse the variables, pulled that from my WIP CMS.

You surprise me, Deathshadow - I would have tought you would have used templates, rather than inline PHP in HTML?

(Edit: I don’t mean this in any offensive way; rather, I’m curious as to why you would set up your code this way, as it’s my impression that you’re very focussed on following best practice).

That IS inside a template FUNCTION… to be precise:

function theme_header($settings) {

in /themes/themename/common.template.php

If you mean templating SYSTEMS like Smarty? The ones that are overglorified versions of printF (a function I also can’t stand for ending up needlessly vague/confusing) – The overhead is wasteful, they’re a pain in the ass to maintain because everything is stored all over the place. I find them a confusing difficult to use mess.

Every time I deal with systems like “smarty”, I feel like screaming “Oh for {nasty expletive omitted} sake, just let me edit the {even nastier expletive omitted} code!!!”

Especially since in many cases they take the logic flow of output out of your hands GREATLY limiting what you can do in them.

Another of the reasons you couldn’t pay me to skin something like Turdpress or myBB… and why I LIKE SMF. So much to like in SMF… one index to rule them all, actually have the theme template system directly in php functions, stuff clearly separated by role into a logical directory structure… not once does it have to try to uptree a include, link, or element embed…

I don’t consider the string parsing “templating” (like Smarty) to be good practice – they are more akin to tying the HTML coders down rump up so they can say “thank you sir may I have another” Kevin Bacon style.

NOT a fan.

Though admittedly, that code is from an older copy… the current function reads more like this:

function theme_header(&$data) {

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
	xmlns="http://www.w3.org/1999/xhtml"
	xml:lang="',$data->settings['language'],'"
	lang="',$data->settings['language'],'"
><head>';

	theme_metaList($data->metaList);

	echo '

<link
	type="text/css"
	rel="stylesheet"
	href="',$data->linkHome,$data->themeDir,'screen.css"
	media="screen,projection,tv"
/>

<title>
	',(
		isset($data->output['pageTitle']) ?
		$data->output['pageTitle'].' - ' :
		''
	),$data->settings['siteTitle'],'
</title>

Though that’s before the current rewrite, which is tightening up the security a LOT.

Not exactly. I’m a rather fanatic do-it-yourself coder, so except for forum software, I build everything from scratch.

This is the main template for one of my sites:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Language" content="en">

  <title>{title}</title>

  <link rel="stylesheet" href="/styles/screen.css" type="text/css" media="screen">
  <link rel="shortcut icon" href="/favicon.ico">

  <!--[if lt IE 8]>
   <link rel="stylesheet" href="/styles/lt-ie8.css" type="text/css" media="screen">
  <![endif]-->

 </head>
 <body>
  <div id="container">
{menu}

   <div id="contents">
    <h1>{title}</h1>
{contents}
   </div>

   <div id="footer">
    <p>Last updated {last_update}. Copyright &copy; Christian Ankerstjerne. <a href="/privacy-policy">Privacy policy</a>.</p>
   </div>
  </div>
 </body>
</html>

I will then load the template into the memory using the output buffer, and do a search-replace for the variables. The advantage of this is that I can do on-the-fly manipulation of the variables as needed, and even do regex search-replace with built-in functions.

I’m upvoting this all the way: not only does the browser stop at that tag and start over again, BUT and most importantly, letting the UA think there’s maybe a possibility that this page could be UTF-7, you are open to an obscure attack where anything between your opening <head> tag and your meta tag could be used to do something nasty, depending on what’s in there. Especially you don’t want script tags before that meta tag.

Of course, this can be avoided by setting with a server header, except for all those UAs who don’t even bother checking those headers (IE6 was actually particularly good making guesses as to the charset based on language heuristics or something… and was then vulnerable to the UTF-7 hack).

Always try to put that tag first after <html lang=“whatever”><head>, and if you’re using HTML5 then <meta charset=“whatever”> will work as well (apparently browsers have been able to read that abomination all along).

Or use a single script in the <head> which is tiny and does nothing more but call all your other scripts. These scripts won’t “block” page load, but will load at the same time as the document like all other resources (such as images). If it’s tiny it will be read and run so fast you won’t notice it.

I found out recently that this tag is no longer recommended… I still believe it does no harm so long as a proper lang (and possible xml:lang if using that) attribute it on the <html> tag… but this nifty i18l checker will flag it as “not recommended for any version of HTML”.

Apparently now we can be 100% safe with the lang declaration in the <html> tag for all relevant UAs.

Just to note, it’s actually best to put whatever Javascript you can into the footer of your page, instead of the head. When Javascript is loaded in browsers, it prevents any other files from being downloaded at the same time (aside from other Javascript), so it’ll delay your page.

If you can, putting it in the footer will let everything else load before the Javascript, so it’ll load up faster.

Of course if you’re doing a lot of layout changes with the Javascript (which I don’t recommend), you’ll likely want the Javascript to be loaded before the rest is loaded, so people don’t see the screen jump.

JS files just before </body> (except for special scripts like modernizr). Try to put all your plugins (when possible of course) in one single file as it increases speed.

Why do you not recommend it? I often make bigish layout changes with JS, to present different interfaces to those with JS off and those with it on. Surely that is required for progressive enhancement?

Well, for more “web application”-esque pages it makes sense. However, I generally avoid major JS-based layout changes whenever I can (trying to present the same appearance to both those with and without JS enabled) for “normal” websites.

There aren’t that many things that can’t be done with Javascript along that warrant (for me) the slow down in page loading that putting it in the header causes.

In the cases where there are (like interactive web-application-esque pages) it makes sense, and I’d probably put just the Javascript required for layouts in one file and all the other Javascript in another file. Then put the layout one in the header and the rest right before </body>.

I honestly think it is irrelevent.
Modern browsers read CSS, Javascript, Markup and then perform a Rendering of the page based on that collective input.

Proper http-equiv meta tags are important to aid the browser in its processing of the stream of data.

If I understand correctly, that’s only while a script is running. The js file is simply text, and unless you include the complete jQuery library, is whiz-bang to load.

Use a document.onload anonymous function at the file’s beginning to make calls only after the document is loaded.

IMO javascript, like styles, does not belong in the body. The files should be linked in the head section.

cheers,

gary

Not quite.

If you read Amazon.com: High Performance Web Sites: Essential Knowledge for Front-End Engineers (9780596529307): Steve Souders: Books, they discuss this at length.

Normally, whenever you load a web page, there are a certain numbers of files downloaded simultaneously. However, most (if not all) browsers, when they come across a Javascript file, will not start any new files, other than Javascript files downloading. That means if you have a large Javascript file, the browser will essentially pause the loading of anything else until that file is complete. The reason behind this is that Javascript scripts are dependent on each other. For example, if you have jQuery and then a script with jQuery, it must load jQuery before the second one can run, so it’ll wait.

That’s why it’s recommended to put it in the footer, since by that point everything else is already loaded.

The exception to this would be if you wanted the Javascript to be loaded (and thus capable of executing) before everything else is loaded.

So the question is, how the hell big are your js files? They’re plain text. They load in a snap unless you’re loading the entire jQuery library, though a novice might do just that. The visitor doesn’t need to wait for the script(s) to run, because they run only as an onload event.

cheers,

gary

Sorry to get a bit OT

AFAIK, an HTML5 javascript shiv would need to run after the DOM loads

My Javascript files are usually as small as possible (I’m quite good at writing well-optimized and tiny code). However, a quarter of a second is still a quarter of a second. The best place for the Javascript scripts is still in the footer, whether their 100 B or 100 MB (previous exception excluded).

It’s all been covered but you might get a lot from reading this, which is where the recommendations are coming from.
Best Practices for Speeding Up Your Web Site

Here’s my summary of them:
Front end standards