The performance of JavaScript in the browser can be considered the most important usability issue that developers face. This problem is complicated by the blocking characteristics of JavaScript, that is, when JavaScript is running, other things cannot be handled by the browser. In fact, most browsers use a single process to handle multiple tasks, such as UI updates and JavaScript runs, and only one task can be executed at the same time.
How long does JavaScript run, and how long the wait time is before the browser is idle to respond to user input?
On the basic level, this means that the presence of <script> tags causes the entire page to wait for the script to parse and run. Whether the actual JavaScript code is inline or contained in an unrelated external file, the page download and parsing process must stop, waiting for the script to complete the processing before continuing. This is an essential part of the page lifecycle because the script may modify the content of the page while it is running.
A typical example is the document.write () function, for example:
When a browser encounters a <script> tag, as in the HTML page above, it is not possible to predict whether JavaScript adds content to the <p> tag. So, the browser stops, runs this JavaScript code, and then continues parsing and translating the page. The same thing happens in the process of loading JavaScript using the SRC attribute. The browser must first download the code for the external file, which takes some time, and then parses and runs the code. In this process, page parsing and user interaction are completely blocked.
HTML 4 documents indicate that a <script> tag can be placed in the
Although the code looks harmless, they do have a performance problem: Three JavaScript files are loaded in the
Keep in mind that the browser does not render any part of the page until it encounters the <body> tag. Putting the script at the top of the page in this way will result in a perceptible delay, usually shown as a blank page when the page is opened, and the user cannot read or interact with the page at this point.
Internet Explorer 8, Firefox 3.5, Safari 4, and Chrome 2 allow JavaScript files to be downloaded in parallel. The good news is that when a <script> tag is downloading an external resource, you do not have to block other <script> tags. Unfortunately, JavaScript downloads still block other resources from downloading, even if the download process between scripts is not blocked, the page still waits until all JavaScript code has been downloaded and executed before continuing. So, when the browser improves performance by allowing concurrent downloads, the problem is not completely resolved, and scripting blocking remains a problem.
Because the script blocks the download process for other page resources, the recommended approach is to place all <script> tabs as close to the bottom of the <body> label as possible, minimizing the impact on the entire page download. For example: