Published on : 26 September 20193 min reading time

When creating web pages, we often read that you have to put the CSS files in head, at the beginning of the HTML document and that you have to put JavaScript at the end. On the other hand, it is rarely said why.

During the process of displaying a web page, the first phase consists in downloading the web page: the HTML document as well as the images, but also the CSS style sheets and related JS scripts.

HTML content is what you see: text, images, search fields, etc.

CSS styles are how HTML will be seen: layout, font colours and text size, background colour of the page.

CSS and HTML are therefore necessary for the display of the web page and therefore for the visitor who wishes to read your site.

JS scripts, on the other hand, are instructions for the browser, not the user. The browser processes them in the background and the user doesn’t see any difference if they are there or not (normally).

The problem is the ability of the SB to modify HTML and CSS. As a result, the browser that receives an HTML+CSS page will actually only has the entire web page once it has finished executing the JS scripts. Before that, he can do (almost) nothing: he will start displaying the different elements of the page (menu, titles, links…) but if the SB deletes the menu in the meantime, he will have to start all over again.

The browser is a solution for the JS problem?

Start rendering (displaying) the page and pause this rendering when it detects a JS script: at that point, it must download the entire JS script and execute it entirely (which is likely to change HTML and CSS, remember) before resuming rendering (and if necessary restart it, if the JS has changed HTML or CSS a lot).

The fact that the browser has to pause when it encounters a script makes us say that the JS is blocking.

CSS, HTML and even images are non-blocking: the browser can continue to decode the web page even while it is still downloading CSS, for example. It can therefore download CSS in parallel with HTML. Once it has all the CSS, it starts rendering as described by the CSS. The decoding of HTML continues throughout this time.

A simple HTML document, without CSS or JS, still appears: it is the default rendering of a web page: the background is white, the text is black and all the elements are in sequence. Anyway, it’s ugly, but it’s still readable.