[翻譯]High Performance JavaScript(002)

Grouping Scripts 成組腳本


    Since each <script> tag blocks the page from rendering during initial download, it's helpful to limit the total number of <script> tags contained in the page. This applies to both inline scripts as well as those in external files. Every time a <script> tag is encountered during the parsing of an HTML page, there is going to be a delay while the code is executed; minimizing these delays improves the overall performance of the page.

    由於每個<script>標籤下載時阻塞頁面解析過程,所以限制頁面的<script>總數也可以改善性能。這個規則對內聯腳本和外部腳本同樣適用。每當頁面解析碰到一個<script>標籤時,緊接着有一段時間用於代碼執行。最小化這些延遲時間可以改善頁面的整體性能。

    The problem is slightly different when dealing with external JavaScript files. Each HTTP request brings with it additional performance overhead, so downloading one single 100 KB file will be faster than downloading four 25 KB files. To that end, it's helpful to limit the number of external script files that your page references. Typically, a large website or web application will have several required JavaScript files. You can minimize the performance impact by concatenating these files together into a single file and then calling that single file with a single <script> tag. The concatenation can happen offline using a build tool (discussed in Chapter 9) or in real-time using a tool such as the Yahoo! combo handler.

    這個問題與外部JavaScript文件處理過程略有不同。每個HTTP請求都會產生額外的性能負擔,下載一個100KB的文件比下載四個25KB的文件要快。總之,減少引用外部腳本文件的數量。典型的,一個大型網站或網頁應用需要多次請求JavaScript文件。你可以將這些文件整合成一個文件,只需要一個<script>標籤引用,就可以減少性能損失。這一系列的工作可通過一個打包工具實現(我們在第9章討論),或者一個實時工具,諸如“Yahoo! combo handler”。
    Yahoo! created the combo handler for use in distributing the Yahoo! User Interface (YUI) library files through their Content Delivery Network (CDN). Any website can pull in any number of YUI files by using a combo-handled URL and specifying the files to include. For example, this URL includes two files:

http://yui.yahooapis.com/combo?2.7.0/build/yahoo/yahoo-min.js&2.7.0/build/event/event-min.js

This URL loads the 2.7.0 versions of the yahoo-min.js and event-min.js files. These files exist separately on the server but are combined when this URL is requested. Instead of using two <script> tags (one to load each file), a single <script> tag can be used to load both:

     Yahoo! 爲他的“Yahoo! 用戶接口(Yahoo! User Interface,YUI)”庫創建一個“聯合句柄”,這是通過他們的“內容投遞網絡(Content Delivery Network,CDN)”實現的。任何一個網站可以使用一個“聯合句柄”URL指出包含YUI文件包中的哪些文件。例如,下面的URL包含兩個文件:

http://yui.yahooapis.com/combo?2.7.0/build/yahoo/yahoo-min.js&2.7.0/build/event/event-min.js
此URL調用2.7.0版本的yahoo-min.js和event-min.js文件。這些文件在服務器上是兩個分離的文件,但是當服務器收到此URL請求時,兩個文件將被合併在一起返回給客戶端。通過這種方法,就不再需要兩個<script>標籤(每個標籤加載一個文件),一個<script>標籤就可以加載他們:

<html>
  <head>
    <title>Script Example</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <p>Hello world!</p>
    <-- Example of recommended script positioning -->
    <script type="text/javascript" src="
http://yui.yahooapis.com/combo?2.7.0/build/yahoo/yahoo-min.js&2.7.0/build/event/event-min.js"></script>
  </body>
</html>

    This code has a single <script> tag at the bottom of the page that loads multiple JavaScript files, showing the best practice for including external JavaScript on an HTML page.

    此代碼只有一個<script>標籤,位於頁面的底部,加載多個JavaScript文件。這是在HTML頁面中包含多個外部JavaScript的最佳方法。


Nonblocking Scripts  非阻塞腳本


    JavaScript's tendency to block browser processes, both HTTP requests and UI updates, is the most notable performance issue facing developers. Keeping JavaScript files small and limiting the number of HTTP requests are only the first steps in creating a responsive web application. The richer the functionality an application requires, the more JavaScript code is required, and so keeping source code small isn't always an option. Limiting yourself to downloading a single large JavaScript file will only result in locking the browser out for a long period of time, despite it being just one HTTP request. To get around this situation, you need to incrementally add more JavaScript to the page in a way that doesn't block the browser.

    JavaScript傾向於阻塞瀏覽器某些處理過程,如HTTP請求和界面刷新,這是開發者面臨的最顯著的性能問題。保持JavaScript文件短小,並限制HTTP請求的數量,只是創建反應迅速的網頁應用的第一步。一個應用程序所包含的功能越多,所需要的JavaScript代碼就越大,保持源碼短小並不總是一種選擇。儘管下載一個大JavaScript文件只產生一次HTTP請求,卻會鎖定瀏覽器一大段時間。爲避開這種情況,你需要向頁面中逐步添加JavaScript,某種程度上說不會阻塞瀏覽器。
    The secret to nonblocking scripts is to load the JavaScript source code after the page has finished loading. In technical terms, this means downloading the code after the window's load event has been fired. There are a few techniques for achieving this result.

    非阻塞腳本的祕密在於,等頁面完成加載之後,再加載JavaScript源碼。從技術角度講,這意味着在window的load事件發出之後開始下載代碼。有幾種方法可以實現這種效果。


Deferred Scripts  延期腳本


    HTML 4 defines an additional attribute for the <script> tag called defer. The defer attribute indicates that the script contained within the element is not going to modify the DOM and therefore execution can be safely deferred until a later point in time. The defer attribute is supported only in Internet Explorer 4+ and Firefox 3.5+, making it less than ideal for a generic cross-browser solution. In other browsers, the defer attribute is simply ignored and so the <script> tag is treated in the default (blocking) manner. Still, this solution is useful if your target browsers support it. The following is an example usage:
<script type="text/javascript" src="file1.js" defer></script>
A <script> tag with defer may be placed anywhere in the document. The JavaScript file will begin downloading at the point that the <script> tag is parsed, but the code will not be executed until the DOM has been completely loaded (before the onload event handler is called). When a deferred JavaScript file is downloaded, it doesn't block the browser's other processes, and so these files can be downloaded in parallel with others on the page.

    HTML 4爲<script>標籤定義了一個擴展屬性:defer。這個defer屬性指明元素中所包含的腳本不打算修改DOM,因此代碼可以稍後執行。defer屬性只被Internet Explorer 4和Firefox 3.5更高版本的瀏覽器所支持,它不是一個理想的跨瀏覽器解決方案。在其他瀏覽器上,defer屬性被忽略,<script>標籤按照默認方式被處理(造成阻塞)。如果瀏覽器支持的話,這種方法仍是一種有用的解決方案。示例如下:

<script type="text/javascript" src="file1.js" defer></script>

一個帶有defer屬性的<script>標籤可以放置在文檔的任何位置。對應的JavaScript文件將在<script>被解析時啓動下載,但代碼不會被執行,直到DOM加載完成(在onload事件句柄被調用之前)。當一個defer的JavaScript文件被下載時,它不會阻塞瀏覽器的其他處理過程,所以這些文件可以與頁面的其他資源一起並行下載。
    Any <script> element marked with defer will not execute until after the DOM has been completely loaded; this holds true for inline scripts as well as for external script files. The following simple page demonstrates how the defer attribute alters the behavior of scripts:

    任何帶有defer屬性的<script>元素在DOM加載完成之前不會被執行,不論是內聯腳本還是外部腳本文件,都是這樣。下面的例子展示了defer屬性如何影響腳本行爲:
<html>
  <head>
    <title>Script Defer Example</title>
  </head>
  <body>
    <script defer>
      alert("defer");
    </script>
    <script>
      alert("script");
    </script>
    <script>
      window.onload = function(){
        alert("load");
      };
    </script>

  </body>
</html>

    This code displays three alerts as the page is being processed. In browsers that don't
support defer, the order of the alerts is “defer”, “script”, and “load”. In browsers that
support defer, the order of the alerts is “script”, “defer”, and “load”. Note that the
deferred <script> element isn't executed until after the second but is executed before
the onload event handler is called.

    這些代碼在頁面處理過程中彈出三個對話框。如果瀏覽器不支持defer屬性,那麼彈出對話框的順序是“defer”,“script”和“load”。如果瀏覽器支持defer屬性,那麼彈出對話框的順序是“script”,“defer”和“load”。注意,標記爲defer的<script>元素不是跟在第二個後面運行,而是在onload事件句柄處理之前被調用。
    If your target browsers include only Internet Explorer and Firefox 3.5, then deferring scripts in this manner can be helpful. If you have a larger cross-section of browsers to support, there are other solutions that work in a more consistent manner.
    如果你的目標瀏覽器只包括Internet Explorer和Firefox 3.5,那麼defer腳本確實有用。如果你需要支持跨領域的多種瀏覽器,那麼還有更一致的實現方式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章