Why is it faster to load HTML and CSS first while loading a page. What are the exceptions to this general rule(if there is any)?
3 Answers 3
Note: This question may be better suited to Webmasters.SE
Your question title and content are different :p
It's not "faster", but it is "better". And it looks faster to the user.
The reason is, loading the HTML first is crucial because it gets the content there in front of your user.
Loading CSS then makes it look pretty. Ideally, it should take zero time to load CSS, which is why CSS is generally a blocking request to avoid the FOUC (Flash Of Unstyled Content) that may occur otherwise.
Finally, JavaScript. This is loaded last because it should not have an effect on the page's appearance. At least, not immediately. Not before user interaction. And since the user is extremely unlikely to have Terminator reflexes and interact with your page in the first few tenths of a second, then it's okay for it to be loaded in just a little later.
Note that I say "should not" above, but that doesn't mean "must not". On my own project, the JavaScript is actually responsible for rendering the navigation bar and other header/footer content - this was done so that the content could be cached and save up to 8Kb of bandwidth for every single pageload - with a few million pageloads per day, that adds up fast! But in this case, space is already reserved for the header/footer, meaning the content itself can begin to be read even in the fraction of a second before header/footer content has been loaded - it's all about getting the important content up and visible first
15 Comments
robots.txt
file to help search engines.CSS files can be loaded in parallel with the HTML. That's why they are generally declared first in the head of the documents to load. Browsers are allotted a few streams where they can load documents in parallel from the same domain. For even better performance, if you can load files from different domains, or subdomains, you can even get better performance as you can load more documents in parallel.
JavaScript files differ in that they are considered blocking, and cannot necessarily be loaded in parallel the same way that CSS files can be. That is why it's generally best practice to load JavaScript files near the end of the document where possible.
style
element in your document'shead
. As per the way StackOverflow works, I've had to vote to close this question for being Primarily Opinion Based.