[翻译]High Performance JavaScript(002)

来源:互联网 发布:邯郸峰派网络 编辑:程序博客网 时间:2024/04/30 06:28

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脚本确实有用。如果你需要支持跨领域的多种浏览器,那么还有更一致的实现方式。

原创粉丝点击