The reason why the JavaScript file is placed at the bottom of the Html is because the browser will execute it after loading the JS file. At this time, if there is an operation on the DOM in the JS, the DOM may not be loaded yet, and an error will occur. In addition, Since JS is of little use for page display, CSS should be loaded first to display the page as quickly as possible.
There are two considerations for this issue:
If it is an externally loaded js, That is, external js loaded through src. The reason why the js called in this way is placed at the bottom is because the browser renders the web page from top to bottom. The page is what the user can see and intuitively feel, and the js code It is something that users cannot see and belongs to the "behind the scenes". If you put the "behind the scenes" things at the bottom, the page that the user can see will load faster, making the user feel that the page opens quickly, which improves the efficiency of the page. user experience.
js is generally used to operate the DOM of the page. If the js code is placed at the top of the page, based on the browser's loading mechanism from top to bottom, there are DOM nodes that may be manipulated. Before loading is complete, JS will operate on the DOM, which will obviously cause errors. It will be safer to put it at the bottom of the page.
The main consideration is the first one. The second one is now in order to 100% ensure that the DOM tree is rendered and JS is executed. Basically, load detection is used.
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Why put JavaScript files at the bottom of Html. For more information, please follow other related articles on the PHP Chinese website!