Why is it generally a good idea to position CSS `<link>`s between `<head></head>` and JS `<script>`s just before `</body>`?
Do you know any exceptions?
In a nutshell, such a placement of CSS
<script>s allows for faster rendering of the page and better overall performance.
<head> is part of the proper specification in building an optimized website. When a page first loads, HTML and CSS are being parsed simultaneously; HTML creates the DOM (Document Object Model) and CSS creates the CSSOM (CSS Object Model). Both are needed to create the visuals in a website, allowing for a quick "first meaningful paint" timing. Placing CSS
<link>s in the
<head> ensures that the stylesheets are loaded and ready for use when the browser starts rendering the page.
This progressive rendering is a metric that sites are measured on in their performance scores. Putting stylesheets near the bottom of the document is what prohibits progressive rendering in many browsers. Some browsers block rendering to avoid having to repaint elements of the page if their styles change. The user is then stuck viewing a blank white page. Other times there can be flashes of unstyled content (FOUC), which show a webpage with no styling applied.
<script>s just before
<script> tags block HTML parsing while they are being downloaded and executed which can slow down the display of your page. Placing the
<script>s at the bottom will allow the HTML to be parsed and displayed to the user first.
An exception for positioning of
<script>s at the bottom is when your script contains
document.write(), but these days it's not a good practice to use
document.write(). Also, placing
<script>s at the bottom means that the browser cannot start downloading the scripts until the entire document is parsed. This ensures your code that needs to manipulate DOM elements will not throw an error and halt the entire script. If you need to put
<script>s in the
<head>, use the
defer attribute, which will achieve the same effect of running the script only after the HTML is parsed but the browser can kick off the network request earlier to download the script.
Keep in mind that putting scripts just before the closing
</body> tag will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document). However, if you have some code you want to run during page load, it will only start executing after the entire page has loaded. If you put those scripts in the
<head> tag, they would start executing before - so on a primed cache the page would actually appear to load faster.
<body> tags are now optional
As per the HTML5 specification, certain HTML tags like
<body> are optional. Google's style guide even recommends removing them to save bytes. However, this practice is still not widely adopted and the performance gain is likely to be minimal and for most sites it's not likely going to matter.