One day, xiao Ming is online to find information, the problems in the project need through access to information to solve it, he saw a headline is very interesting, think it should be he want to find the answer, he points to go in, the results into the web site after a few seconds, web page or a blank, after a long time to load.
Why is this happening?
Speaking of which, it is necessary to understand the whole process of website loading.
1. First the browser receives the HTML code from the server and begins parsing the HTML
2. Build the DOM tree (top down from the HTML code) and build the render tree at the same time
3. Js file loading execution will block DOM tree construction; A CSS file is encountered, blocking the build of the render tree
The defer property in the Script tag: building the DOM tree and loading the JS file take place asynchronously (in parallel), but the JS file execution needs to take place after the DOM tree is built
Async properties in script tags: DOM tree building, tree rendering, and JS file loading and execution occur asynchronously (in parallel)
Why change the placement of CSS and JS?
When the js file is placed in the head, the browser will block the loading of the JS file when building the DOM tree. That is, the browser will not load the tag in the body. Once the number and content of the JS file are too large, this will cause the situation that Ming encountered just now. You don’t give the user a very good visual feedback, which is very important in front end development.
We now like to describe a process with a progress bar, and the visual feedback to the user is the progress bar for the page to load.
For today’s fast-paced people, if a web page opens and doesn’t respond within two seconds, or loads slowly, users will be impatient to shut it down, as if it were a death sentence.
Where should I put it?
In summary, it is best to place the script tag before the body tag, because after all the body tags there is no blank page loading, it provides continuous visual feedback to the user, and in some cases, it reduces errors.
The CSS tag should be placed between the head tag, because if you put it before the body tag, the render tree will be built when the DOM tree is completed, and when the render tree is completed, the browser will have to re-render the entire page, resulting in a waste of resources. It’s not very efficient. If placed between heads, the browser builds as it renders, which is much more efficient.
(If you have any shortcomings or mistakes, please kindly comment on them.)