CHAPTER 5, Rule 5: Put Stylesheets at the Top
- we want the browser to display whatever content it has as soon as possible (load progressively)
- putting stylesheets near the bottom of the document prohibits progressive rendering in many browsers as components are (in general) downloaded in the order in which they appear in the document.
- Browsers block rendering to avoid having to redraw elements of the page if their styles change (which means, browsers wait until all stylesheets are loaded before calculating the style of the loaded elments).
So basically the Rule is : Put your stylesheets in the document HEAD using the LINK tag.
CHAPTER 6, Rule 6: Put Scripts at the Bottom
- Experiment: put a script in the middle of a page, programm the script to take 10 seconds to load, you will notice the problem which is the bottom half of the page takes about 10 seconds to appear.
- As we mentioned before, when using stylesheets, progressive rendering is blocked until all stylesheets have been downloaded.That’s why it’s best to move stylesheets to the document HEAD, so they are downloaded first and rendering isn’t blocked. However, with scripts, progressive rendering is blocked for all content below the script.Moving scripts lower in the page means more content is rendered progressively.
- HTTP/1.1 specification suggests that
browsers download two components in parallel per hostname, so if you are downloading from the same hostname you will see something like this
However, if you are downloading from 2 hostnames, you will find 4 parallel download bars,
- Note that for HTTP/1.0, Firefox’s default is to download eight components on parrallel, you can change these value in the browser configuration.
- To increase parallel downloaded components, use CNAMEs (DNS aliases) to split their components across multiple hostnames.
- Too many parallel downloads can degrade performance.Research at Yahoo! shows that splitting components across two hostnames leads to better performance than using 1, 4, or 10 hostnames
Scripts Block Downloads
- Parallel downloading is disabled while a script is downloading—the browser won’t start any other downloads, even on different hostnames
- This is to guarantee that the scripts are executed in the proper order.If multiple scripts were downloaded in parallel, there’s no guarantee the responses would arrive in the order specified.
- Also because the script may use document.write to alter the page content, so the browser waits to make sure the page is laid out appropriately.
So if we put the scripts at the top (this is the worst case):
- Content below the script is blocked from rendering.
- Components below the script are blocked from being downloaded.
But if we put the scripts at the bottom (this is the best case):
- The page contents aren’t blocked from rendering
- Viewable components in the page are downloaded as early as possible
That's why we should Move scripts to the bottom of the page.