Order of tags in <head></head> - html

does it matter at all what order the <link> or <script> or <meta> tags are in in the <head></head>?
(daft question but one of those things i've never given any thought to until now.)

Optimization
According to the folks over at Yahoo! you should put CSS at the top and scripts at the bottom because scripts block parallel downloads. But that is mostly a matter of optimization and is not critical for the page actually working. Joeri Sebrechts pointed out that Cuzillion is a great way to test this and see the speed improvement for yourself.
Multiple Stylesheets
If you are linking multiple stylesheets, the order they are linked may affect how your pages are styled depending on the specificity of your selectors. In other words, if you have two stylesheets that define the same selector in two different ways, the latter will take precedence. For example:
Stylesheet 1:
h1 { color: #f00; }
Stylesheet 2:
h1 { color: #00f; }
In this example, h1 elements will have the color #00f because it was defined last with the same specificity:
Multiple Scripts
If you are using multiple scripts, the order they are used may be important if one of the scripts depends on something in another script. In this case, if the scripts are linked in the wrong order, some of your scripts may throw errors or not work as expected. This, however, is highly dependent on what scripts you are using.

The accepted answer is kind of wrong, depending on the encoding of the document. If no encoding is sent by in the HTTP header, the browser has to determine the encoding from the document itself.
If the document uses a <meta http-equiv="Content-Type" … declaration to declare its encoding, then any ASCII-valued character (character code < 128) occurring before this statement must be an ASCII value, as per HTML 4 spec. Therefore, it's important that this meta declaration occurs before any other element that may contain non-ASCII characters.

It's recommended to put the meta tag with the character encoding as high as possible. If the encoding is not included in (or differs from) the response header of the requested page, the browser will have to guess what the encoding is. Only when it finds this meta tag it knows what it is dealing with and it will have to read everything it has already parsed again.
See for instance Methods for indicating the character set.

One important thing to note: if you're using the Internet Explorer meta X-UA-Compatible tag to switch rendering modes for IE, it needs to be the first thing in the HEAD:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>Page title</title>
...etc
&lt/head>

meta does not matter, but link (for css) and script matters.
script will block most browser from rendering the page until the scripts are loaded.
Therefore, if possible put them not in the head, but the body.
css link will not block page rendering.

It is usually recommended to have the <script> tag as lower down the page as possible (not in the head but in the body).
Other than that, I don't think it makes much of a difference because the body cannot be parsed unless you have the <head> section completely loaded. And, you want your <link> tag to be in the head as you want your styling to occur as the browser renders your page and not after that!

If you declare the charset in a meta element, you should do it before any other element.

Not a daft question at all.
CSS above Script tags for reasons already mentioned.
CSS is applied in the order you place the tags - the more specific the stylesheet, the lower down the order it should be.
Same goes for scripts - scripts that use functions declared in other files should be loaded after the dependency is loaded.

Put the meta tag that declares the charset as the first element in head. The browser only searches so far for the tag. If you have too much stuff before the meta element, the charset might not get applied.
If you use the BASE element, put it before any elements that load URIs (if desired).

It would only matter if one of the linked files (CSS/Javascript) depended on another. In that case, all dependencies must be loaded first.
Say, for example, you are loading a jQuery plugin, you'd then need to first load jQuery itself. Same when you have a CSS file with some rules extending other rules.

As already pointed out meta describing content charset should be the first otherwise it could actually be a security hole in a certain situation. (sorry i dont remember that situation well enought to describe here but it was demostrated to me at web security training course)

I recently was having a problem with a draggable jquery ui element. It was behaving properly in Firefox, but not Safari. After a ton of trial and error, the fix was to move my css links above the javascript links in the head. Very odd, but will now become my standard practice.

For the purposes of validation as XHTML, yes. Otherwise you're probably going to care about the optimization answers.

Nope, it doesn't matter, except for CSS linking or inclusion, because of CSS inheritance and the fact that it overwrite what was already styled (sorry for my english, i think my sentence is not really clear :-/).

Related

Link a Stylesheet (CSS) outside of the HEAD Tag

I have seen a number of questions regarding this issue and I have yet to see the response I am looking for. I simply want to know if it is possible to link to an external stylesheet anywhere else other than the HEAD tag.
The reason I ask, is I have to use Confluence to document and the addons our company uses are very basic. I wanted to style my page but the issue is that Confluence innately overrides any HEAD tag and inserts its own. There is no way to get around this without the HTML addon, which my company will not purchase.
To get around this, I have to include a large STYLE tag with all of the styled customizations so it can get fairly long.
I am just looking to see if it is possible and how to link a stylesheet anywhere else in the HTML other than the HEAD tag. (I am aware that this is not common or good practice, and I also understand the reasons for having the stylesheet in the HEAD tag so please no comments regarding this.)
Yes, it's possible to include a stylesheet somewhere else other than <head> - precisely, you can place it inside <body>. To quote MDN:
A <link> tag can occur either in the head element or in the body
element (or both), depending on whether it has a link type that is
body-ok. For example, the stylesheet link type is body-ok, and
therefore a <link rel="stylesheet"> is permitted in the body.

HTML Style Guide Google vs W3Schools (Omit Optional Tag)

I was reading some style guides and saw a conflicting recomandation
regarding the Optional Tags.
Google says:
Omit optional tags (optional). For file size optimization and
scannability purposes, consider omitting optional tags. The HTML5
specification defines what tags can be omitted.
(This approach may require a grace period to be established as a wider
guideline as it’s significantly different from what web developers are
typically taught. For consistency and simplicity reasons it’s best
served omitting all optional tags, not just a selection.)
W3CSchools says:
Close All HTML Elements In HTML5, you don't have to close all elements
(for example the <p> element).
We recommend closing all HTML elements:
And
We do not recommend omitting the < html > and < body > tags.
This means Google prefers:
<!-- Recommended -->
<!DOCTYPE html>
<title>Saving money, saving bytes</title>
<p>Qed.
W3CSchools prefers:
<!DOCTYPE html>
<html>
<title>Page Title</title>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
it is also considered "bad looking" to write this whereas google would recommend it.
<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>
I found it very interesting that W3CSchools makes a difference regarding the head tag
Is there any good reason to stop using the optional Tags ?
Personally I found the code then less readable but that is purely opinion based and I guess with some training I would prefer one over the other.
Google stated that its for size optimization and scannability purposes but is that really a good reason ? The articles below stated some suggestions but seemed to me more opinion based and I am looking for good reasons to stop using the optional Tags
Here the resources:
Google Style guid
HTML5 Style Guide
html-include-or-exclude-optional-closing-tags
Omitting optional tags of html
Many times we use the optional closing tags because it makes the document more readable. As Google says, removing them reduces file size but, then, most of us don't have the traffic Google does. That suggestion is for those who do. Then, again, reducing download size is always a good thing.
I often leave out the body tag altogether because even the opening tag is optional in most cases. However, there is a danger that leaving that out, and leaving out closing tags, may cause issues later on. I would say putting body tags in and closing all elements removes the possibility of causing those issues. For example, you can only leave the html and body tags out under certain situations.
Reading the spec:
An html element's start tag can be omitted if the first thing inside
the html element is not a comment. An html element's end tag can be
omitted if the html element is not immediately followed by a comment.
For some, this is very important. To others it's not.
It can be more of an issue for dynamically generated sites where the content is created on the fly and the surrounding elements may not be known. Does one really know that the following element will cause a div element to be closed?
Another opinion:
If your site uses gzip compression, DO go out of your way to include the optional tags, speaking at least if in very large tables where so many cell tags are repeated.
If omitted, the original file size is smaller, but then the receiving browser just has to spend time putting every optional tag back in. They will be in the displayed html file. Look at the displayed page source and you will see this is true. So omission is a balance of faster download speed and slower display recovery speed.
But if gzip and the tags are included, gzip compression will compress away the repeated tags, and the transmitted file is no larger than if not included (so absolutely no download savings). And then the browser does not have to spend any time adding every one of them back in. And they ARE going to be added back in. And if hundreds or more cells in a table, this time might add up.
So if gzip, omitting HTML optional tags seems a minus for speed, not a plus (certainly at least in the case of very large tables). Your web host likely provides an feature to add gzip compression.
Single tags like /body or /tbody can't matter to speed, but /td and /tr can be very numerous in large tables.

Is it legit for elements to appear after </html>?

Google PageSpeed Insights recommend us to defer loading of secondary stylesheets by placing them after the closing </html> tag. Code example from that page:
<html>
<head>
<style>
.blue{color:blue;}
</style>
</head>
<body>
<div class="blue">
Hello, world!
</div>
</body>
</html>
<link rel="stylesheet" href="deferred_stylesheet.css">
This strikes me as odd, because I would expect Google to recommend standard practices instead of non-standard practices.
Is the code above legit? Do the HTML5 standards provide consistent rules for browsers to parse these sort of code?
What problems will we (or our users in fact) encounter if we use the tags as such?
It isn't correct to put anything outside the HTML tags however all browsers try to sort the mess they get served.
Almost all browsers e.g. Firefox, Google Chrome, Internet Explorer, etc will sort this out for you. Some self written browsers maybe won't do this.
However you can better write it in between the head tag for performance (because then the browsers don't need to sort out the dirty coding).
This means users will encounter almost no problems.
First, you're missing your <!DOCTYPE html> declaration at the top, which is required for HTML5 documents.
Second, you're also missing a <title> tag in your head.
Finally, no, tags after the closing </html> tag are not allowed. If you run your doc through the w3 validator service you'll see:
Line 14, Column 54: Stray start tag link.
<link rel="stylesheet" href="deferred_stylesheet.css">
This error is unrecoverable.
I would expect to face browsers either totally ignoring it or loading it. Depending on the browser, the version and the platform. Since you can't be sure it'll work (and since it's non-conforming), you shouldn't do it.
UPDATE
This is non-valid HTML, however user-agents are allowed to parse it and include in the body. But they are not required to since they can define their own rules for parse errors
Is this correct or even allowed structure?
No. It is incorrect to place elements outside the <html>tag.
Oh dear! Will it land me in problems?
No. Browsers will fix your bad code as best as it can. This is no problem for the browser.
Should I do it?
Well ... it's complicated. Short answer is "no, probably not". As developers, it is our responsibility to ensure that our code is correct (machines can't be trusted, that will be our downfall!). The rules are there for a reason. On the other hand, as hackers, we can some times break and bend rules, if it makes sense in the situation and you know what the consequenses will be.
HTML hacking? What the hell are you talking about?
Browsers will always try to render the document as best as it can. Interestingly, you don't even have to give the a <html> tag – the browser will figure it out for you.
Here's an example page – inspect the rendered DOM, and the view source. I've almost not given it anything to work with, and it has kindly created all missing tags. Neat! You do need a DOCTYPE declaration and in most cases a <title> tag.
But, I digress ...
So, the browser will definitely render it correctly. It is, however, incorrect as per the specs, and the document will not validate (if you care about that). For the most part, it's a good idea to follow the specs, unless you have a good reason.
Now, I can't see why Google wants you to place it outside the <html> tag. It sounds strange, however I guess they know what they're doing. My guess is, that they want to make absolutely sure, that the ressource is loaded last.

Is there any difference where style tag is located (head vs body) [duplicate]

Normally css files are put inside <head></head>, what if I put it inside <body></body>, what difference will it make?
Just to add on to what jdelStrother has mentioned about w3 specs and ARTstudio about browser rendering.
It is recommended because when you have the CSS declared before <body> starts, your styles has actually loaded already. So very quickly users see something appear on their screen (e.g. background colors). If not, users see blank screen for some time before the CSS reaches the user.
Also, if you leave the styles somewhere in the <body>, the browser has to re-render the page (new and old when loading) when the styles declared has been parsed.
The most recent versions of the HTML spec now permits the <style> tag within body elements. https://www.w3.org/TR/html5/dom.html#flow-content
Also the scoped attribute which used to be prerequisite to have a style tag in the body is now obsolete.
This means, that you can use the style tag everywhere you want, the only implications are decreased page performance due to possible reflows/repaints once the browser hits styles further down in the page tree.
Obsolete answer:
The <style> tag isn't allowed within <body> according to the w3 specs. (You can, of course, apply inline styles via <div style="color:red"> if necessary, but it's generally considered poor separation of style & content)
Putting CSS in body means it is loaded later. It is a technique some use to let the browser start drawing the interface faster (i.e., it removes a blocking step). This is important for user experience on SmartPhones.
I do my best to keep one small css on the <head> and I move the rest at the bottom. For example, if a page uses JQuery UI CSS, I always move it at the bottom of the <body>, just before the links to JQuery javascript. At least, all the non Jquery item can already be drawn.
Head is designed for (Quoting the W3C):
"information about the current
document, such as its title, keywords
that may be useful to search engines,
and other data that is not considered
document content"
See the Global structure of an HTML document. As CSS is not document content, it should be in the head.
Also every other Web developer will expect to see it there, so don't confuse things by putting it in the body, even if it works!
The only CSS you should put in the body is inline CSS, though I usually avoid inline styles.
The standards (HTML 4.01: the style element) clearly specifies that the style tag is only allowed inside the head tag. If you put style tags in the body tag the browsers will try to make the best of it anyway, if possible.
It's possible that a browser would ignore a style tag in the body if you specify a strict document type. I don't know if any current browser does this, but I wouldn't count on all future versions to be so relaxed about where you place the style element.
Although the style tag is not allowed in the body, the link tag is, so as long as you are referencing an external stylesheet, all browsers should render and use the CSS correctly when used in the body.
Source: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
In addition to earlier answers, though putting a style code block inside the element may work in modern browsers (though that still doesn't make it right), there's always a danger, particularly with older browsers that the browser will render the code as text unless the style section's included within a CDATA section.
Of course the other thing with putting it inside the element, other than inline styles, is that as it doesn't meet with the W3C HTML/XHTML specs is that any page with it within the body will fail on the W3C validator. It's always easier to bug-hunt unexpected display problems if all your code is valid, making it easier to spot mistakes. An invalid HTML element can adversely effect the rending of any and all element beyond where it occurs in the code, so you can get unexpected effects having elements in places where they shouldn't be, because when a browser finds an invalid element, it just makes it's best guess as to how it should display it, and different browsers may make different decisions in how they render it.
Whether you use a transitional or a strict doctype, it would still be invalid according to the (X)HTML specs.
Two conflicting answers:
From MDN page on link tag:
A <link> element can occur either in the <head> or <body>
element, depending on whether it has a link type that is body-ok. For
example, the stylesheet link type is body-ok, and therefore a
<link rel="stylesheet"> is permitted in the body. This isn't however
best practice; it makes more sense to separate your <link> elements
from your body content, putting them in your head.
From CSS The Definitive Guide (4th Edition/2017) page 10
To successfully load an external stylesheet, link must be placed inside the head element but may not be placed in any other element.
You would actually defeat the purpose of using CSS by putting the styles in the body. The point would be to separate content from presentation (and function). This way, any changes to style can be done in the stylesheet, not in the content. Once you use the inline style method, every page that has inline styling needs to changed one by one. Tedious, and risky since you could miss a page or three, or ten.
Using a stylesheet, you only need to change the stylesheet; the changes propagate automagically to every HTML page that links to the stylesheet.
neonble's point is also another great reason; if you mess up the HTML by adding CSS inline, rendering becomes a problem. HTML doesn't throw exceptions to your code. Instead it goes out and renders it the best way it can, and moves on.
Adhering to web standards by using a stylesheet makes for a better website. And when you need help because things on your page aren't exactly that way you want them, placing your CSS in the head as opposed to the body makes for much better troubleshooting by yourself and for anyone you ask for help from.
The difference is.
The loading of the page is asynchronous, so if you have external stylesheet it will load the css file immediately when it reach the link tag, that is why it is good to have at the top in head.
What difference will it make?
Pros: Sometimes easier to apply certain attributes in certain places, especially if code is being generated on the fly (such as building via php and each of a dynamically sized list needs its own class... such as for item timings for transforms).
Cons: Slightly slower, may not work someday in the distant future.
My General opinion on it:
Don't do it it you don't have to, but if you do have to, don't lose any sleep over it.
Putting the <style> in the body works well with all modern browsers.
I had been using this in eBay.
If it works, don't kick it.

What's the difference if I put css file inside <head> or <body>?

Normally css files are put inside <head></head>, what if I put it inside <body></body>, what difference will it make?
Just to add on to what jdelStrother has mentioned about w3 specs and ARTstudio about browser rendering.
It is recommended because when you have the CSS declared before <body> starts, your styles has actually loaded already. So very quickly users see something appear on their screen (e.g. background colors). If not, users see blank screen for some time before the CSS reaches the user.
Also, if you leave the styles somewhere in the <body>, the browser has to re-render the page (new and old when loading) when the styles declared has been parsed.
The most recent versions of the HTML spec now permits the <style> tag within body elements. https://www.w3.org/TR/html5/dom.html#flow-content
Also the scoped attribute which used to be prerequisite to have a style tag in the body is now obsolete.
This means, that you can use the style tag everywhere you want, the only implications are decreased page performance due to possible reflows/repaints once the browser hits styles further down in the page tree.
Obsolete answer:
The <style> tag isn't allowed within <body> according to the w3 specs. (You can, of course, apply inline styles via <div style="color:red"> if necessary, but it's generally considered poor separation of style & content)
Putting CSS in body means it is loaded later. It is a technique some use to let the browser start drawing the interface faster (i.e., it removes a blocking step). This is important for user experience on SmartPhones.
I do my best to keep one small css on the <head> and I move the rest at the bottom. For example, if a page uses JQuery UI CSS, I always move it at the bottom of the <body>, just before the links to JQuery javascript. At least, all the non Jquery item can already be drawn.
Head is designed for (Quoting the W3C):
"information about the current
document, such as its title, keywords
that may be useful to search engines,
and other data that is not considered
document content"
See the Global structure of an HTML document. As CSS is not document content, it should be in the head.
Also every other Web developer will expect to see it there, so don't confuse things by putting it in the body, even if it works!
The only CSS you should put in the body is inline CSS, though I usually avoid inline styles.
The standards (HTML 4.01: the style element) clearly specifies that the style tag is only allowed inside the head tag. If you put style tags in the body tag the browsers will try to make the best of it anyway, if possible.
It's possible that a browser would ignore a style tag in the body if you specify a strict document type. I don't know if any current browser does this, but I wouldn't count on all future versions to be so relaxed about where you place the style element.
Although the style tag is not allowed in the body, the link tag is, so as long as you are referencing an external stylesheet, all browsers should render and use the CSS correctly when used in the body.
Source: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
In addition to earlier answers, though putting a style code block inside the element may work in modern browsers (though that still doesn't make it right), there's always a danger, particularly with older browsers that the browser will render the code as text unless the style section's included within a CDATA section.
Of course the other thing with putting it inside the element, other than inline styles, is that as it doesn't meet with the W3C HTML/XHTML specs is that any page with it within the body will fail on the W3C validator. It's always easier to bug-hunt unexpected display problems if all your code is valid, making it easier to spot mistakes. An invalid HTML element can adversely effect the rending of any and all element beyond where it occurs in the code, so you can get unexpected effects having elements in places where they shouldn't be, because when a browser finds an invalid element, it just makes it's best guess as to how it should display it, and different browsers may make different decisions in how they render it.
Whether you use a transitional or a strict doctype, it would still be invalid according to the (X)HTML specs.
Two conflicting answers:
From MDN page on link tag:
A <link> element can occur either in the <head> or <body>
element, depending on whether it has a link type that is body-ok. For
example, the stylesheet link type is body-ok, and therefore a
<link rel="stylesheet"> is permitted in the body. This isn't however
best practice; it makes more sense to separate your <link> elements
from your body content, putting them in your head.
From CSS The Definitive Guide (4th Edition/2017) page 10
To successfully load an external stylesheet, link must be placed inside the head element but may not be placed in any other element.
You would actually defeat the purpose of using CSS by putting the styles in the body. The point would be to separate content from presentation (and function). This way, any changes to style can be done in the stylesheet, not in the content. Once you use the inline style method, every page that has inline styling needs to changed one by one. Tedious, and risky since you could miss a page or three, or ten.
Using a stylesheet, you only need to change the stylesheet; the changes propagate automagically to every HTML page that links to the stylesheet.
neonble's point is also another great reason; if you mess up the HTML by adding CSS inline, rendering becomes a problem. HTML doesn't throw exceptions to your code. Instead it goes out and renders it the best way it can, and moves on.
Adhering to web standards by using a stylesheet makes for a better website. And when you need help because things on your page aren't exactly that way you want them, placing your CSS in the head as opposed to the body makes for much better troubleshooting by yourself and for anyone you ask for help from.
The difference is.
The loading of the page is asynchronous, so if you have external stylesheet it will load the css file immediately when it reach the link tag, that is why it is good to have at the top in head.
What difference will it make?
Pros: Sometimes easier to apply certain attributes in certain places, especially if code is being generated on the fly (such as building via php and each of a dynamically sized list needs its own class... such as for item timings for transforms).
Cons: Slightly slower, may not work someday in the distant future.
My General opinion on it:
Don't do it it you don't have to, but if you do have to, don't lose any sleep over it.
Putting the <style> in the body works well with all modern browsers.
I had been using this in eBay.
If it works, don't kick it.