The performance of Javascript in the browser can be said to be the most important usability issue faced by front-end developers.
Among Yahoo’s Yslow 23 rules, one of them is to put JS at the bottom. The reason is that, in fact, most browsers use a single process to handle multiple tasks such as UI and updating Javascript, and only one task can be executed at a time. How long the Javascript is running, then how long it waits before the browser becomes idle to respond to user interaction.
At a basic level, this means that the presence of the <script> tag causes the entire page to wait for the script to be parsed and run. Regardless of whether the actual JavaScript code is inline or contained in an unrelated external file, the page download and parsing process must stop and wait for the script to complete this processing before continuing. This is an essential part of the page lifecycle, since the script may modify the page content while running. A typical example is the document.write() function, for example: <br>
</p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="5199" class="copybut" id="copybut5199" onclick="doCopy('code5199')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code5199">
<br>
<html><br>
<head><br>
<title>Script Example</title><br>
</head> <br>
<br>
<body><br>
<p><br>
<script type="text/javascript"><br>
document.write("The date is " (new Date()).toDateString());<br>
</p><br>
</body> <br>
</html><br>
<br>
</div>
When the browser encounters a <script> tag, as in the HTML page above, there is no way to predict whether JavaScript will add content in the <p> tag. Therefore, the browser stops, runs this JavaScript code, and then continues parsing and translating the page. The same thing happens when loading JavaScript using the src attribute. The browser must first download the code for the external file, which takes some time, and then parse and run the code. During this process, page parsing and user interaction are completely blocked. <br>
Because scripts block the download process of other page resources, the recommended approach is to place all <script> tags as close to the bottom of the <body> tag as possible to minimize the impact on the download of the entire page. For example: <p>
<br></p>
<div class="codetitle"><span><a style="CURSOR: pointer" data="96913" class="copybut" id="copybut96913" onclick="doCopy('code96913')">Copy code<u></u></a> The code is as follows:</span></div>
<div class="codebody" id="code96913">
<html><br>
<head><br>
<title>Script Example</title><br>
<link rel="stylesheet" type="text/css" href="styles.css"> <br>
</head><br>
<br>
<body><br>
<p>Hello world!</p><br>
<-- Example of recommended script positioning --> <br>
<script type="text/javascript" src="file1.js"></script>