日期:2014-05-16 浏览次数:20394 次
一.Loading and Execution
?? JavaScript performance in the browser is arguably the most important usability issue facing developers. The problem is complex because of the blocking nature of JavaScript, which is to say that nothing else can happen while JavaScript code is being executed.
??? In fact, most browsers use a single process for both user interface (UI) updates and JavaScript execution, so only one can happen at any given moment in time. The longer JavaScript takes to execute, the longer it takes before the browser is free to respond to user input.
??? On a basic level, this means that the very presence of a <script> tag is enough to make the page wait for the script to be parsed and executed. Whether the actual JavaScript code is inline with the tag or included in an external file is irrelevant; the page download and rendering must stop and wait for the script to complete before proceeding. This is a necessary part of the page’s life cycle because the script may cause changes to the page while executing. The typical example is using document.write() in the middle of a page (as often used by advertisements).
??? When the browser encounters a <script> tag, as in this HTML page, there is no way?of knowing whether the JavaScript will insert content into the <p>, introduce additional?elements, or perhaps even close the tag. Therefore, the browser stops processing the?page as it comes in, executes the JavaScript code, then continues parsing and rendering?the page. The same takes place for JavaScript loaded using the src attribute; the browser?must first download the code from the external file, which takes time, and then parse?and execute the code. Page rendering and user interaction are completely blocked during?this time.
<html> <head> <title>Script Example</title> <-- Example of inefficient script positioning --> <script type="text/javascript" src="file1.js"></script > <script type="text/javascript" src="file2.js"></script > <script type="text/javascript" src="file3.js"></script > <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <p>Hello world!</p> </body> </html>?? Though this code seems innocuous, it actually has a severe performance issue: there are three JavaScript files being loaded in the <head>. Since each <script> tag blocks the page from continuing to render until it has fully downloaded and executed the JavaScript code, the perceived performance of this page will suffer. Keep in mind that browsers don’t start rendering anything on the page until the opening <body> tag is encountered. Putting scripts at the top of the page in this way typically leads to a noticeable delay, often in the form of a blank white page, before the user can even begin reading or otherwise interacting with the page.