[翻译]High Performance JavaScript(031)

Firebug

 

    Firefox is a popular browser with developers, partially due to the Firebug addon (available at http://www.getfirebug.com/), which was developed initially by Joe Hewitt and is now maintained by the Mozilla Foundation. This tool has increased the productivity of web developers worldwide by providing insights into code that were never before possible.

    对开发人员来说,Firefox是一个时髦的浏览器,部分原因是Firebug插件(http://www.getfirebug.com/)由Joe Hewitt首创现在由Mozilla基金会维护。此工具具有前所未有的代码洞察力,提高了全世界网页开发者的生产力。

 

    Firebug provides a console for logging output, a traversable DOM tree of the current page, style information, the ability to introspect DOM and JavaScript objects, and more. It also includes a profiler and network analyzer, which will be the focus of this section. Firebug is also highly extensible, enabling custom panels to be easily added.

    Firebug提供了一个控制台日志输出,当前页面的DOM树显示,样式信息,能够反观DOM和JavaScript对象,以及更多功能。它还包括一个性能和网络分析器,这是本节的重点。Firebug易于扩展,可添加自定义面板。

 

Console Panel Profiler  控制台面板分析器

 

    The Firebug Profiler is available as part of the Console panel (see Figure 10-1). It measures and reports on the execution of JavaScript on the page. The report details each function that is called while the profiler is running, providing highly accurate performance data and valuable insights into what may be causing scripts to run slowly.

    Firebug分析器是控制台面板的一部分(如图10-1)。它测量并报告页面中运行的JavaScript。当分析器运行时,报告深入到每个被调用函数的细节,提供高精确的性能数据和变量察看功能,(有助于)找出可能导致脚本运行变慢的原因。

Figure 10-1. FireBug Console panel

图 10-1  FireBug控制台面板

 

    One way to run a profile is by clicking the Profile button, triggering the script, and clicking the Profile button again to stop profiling. Figure 10-2 shows a typical report of the profile data. This includes Calls, the number of times the function was called; Own Time, the time spent in the function itself; and Time, the overall time spent in a function and any function it may have called. The profiling is instrumented at the browser chrome level, so there is minimal overhead when profiling from the Console panel.

    点击Profile按钮可启动分析过程,触发脚本,再次点击Profile按钮可停止分析。图10-2显示了一个典型的分析数据报告。它包括Calls:函数被调用的次数;Own Time:函数自身运行花费的时间;Time:函数花费的总时间,包括被它调用的函数所花费的时间总和。性能分析过程在浏览器底层调用,所以从控制台面板启动分析时性能开销很小。

Figure 10-2. Firebug Profile panel

图10-2  Firebug性能面板

 

Console API  终端API

 

    Firebug also provides a JavaScript interface to start and stop the profiler. This allows more precise control over which parts of the code are being measured. This also provides the option to name the report, which is valuable when comparing various optimization techniques.

    Firebug还提供了JavaScript接口用于启动和停止分析器。这可精确控制测量某部分代码。它还提供选项以命名报告,在比较不同的优化技术时特别有价值。

 

console.profile("regexTest");
regexTest('foobar', 'foo');
console.profileEnd();
console.profile("indexOfTest");
indexOfTest('foobar', 'foo');
console.profileEnd();

    Starting and stopping the profiler at the more interesting moments minimizes side effects and clutter from other scripts that may be running. One thing to keep in mind when invoking the profiler in this manner is that it does add overhead to the script. This is primarily due to the time required to generate the report after calling profileEnd(), which blocks subsequent execution until the report has been generated. Larger reports will take longer to generate, and may benefit from wrapping the call to profileEnd() in a setTimeout, making the report generation asynchronous and unblocking script execution.

    在兴趣点上启动和停止分析器,可减少副作用和其他运行脚本造成的干扰。有一点要记住,以这种方法调用分析器会增加脚本的开销。主要是因为调用profileEnd()需要花费时间来生成报告,它阻塞后续执行直到报告生成完毕。较大报告需要更长时间来生成,更好的做法是将profileEnd()调用封装在setTimeout中,使报告生成过程可以异步进行而不阻塞脚本运行。

 

    After ending the profile, a new report is generated, showing how long each function took, the number of times called, the percent of the total overhead, and other interesting data. This will provide insight as to where time should be spent optimizing function speeds and minimizing calls.

    分析完成之后,生成了一份新的报告,显示出每个函数占用了多长时间,被调用的次数,占总开销的百分比,还有其它感兴趣的数据。这些数据为功夫应当花在优化函数速度上,还是减少调用次数上提供了依据。

 

    Like the YUI Profiler, Firebug's console.time() function can help measure loops and other operations that the profiler does not monitor. For example, the following times a small section of code containing a loop:

    正如YUI分析器,Firebug的console.time()函数有助于测量循环和其他分析器不能监视的操作。例如,下面对一小段包含循环的代码进行计时:

 

console.time("cache node");
for (var box = document.getElementById("box"),
     i = 0;
     i < 100; i++) {
  value = parseFloat(box.style.left) + 10;
  box.style.left = value + "px";
}
console.timeEnd("cache node");

    After ending the timer, the time is output to the Console. This can be useful when comparing various optimization approaches. Additional timings can be captured and logged to the Console, making it easy to analyze results side by side. For example, to compare caching the node reference with caching a reference to the node's style, all that is needed is to write the implementation and drop in the timing code:

    在定时器结束之后,时间被输出到控制带上。这可用于比较各种优化方法。控制台可以捕获并记录额外的计时结果,因此很容易并排(显示)分析结果。例如,比较缓存节点引用和缓存节点样式的引用,都需要在计时程序中添加实现代码:

 

console.time("cache style");
for (var style = document.getElementById("box").style,
     i = 0;
     i < 100; i++) {
  value = parseFloat(style.left) + 10;
  style.left = value + "px";
}
console.timeEnd("cache style");

    The Console API gives programmers the flexibility to instrument profiling code at various layers, and consolidates the results into reports that can be analyzed in many interesting ways.

    控制台API使程序员能够灵活地调用不同层次的分析代码,并将结果汇总在报告中,可以用许多感兴趣的方法进行分析。

 

Net Panel  网络面板

 

    Often when encountering performance issues, it is good to step back from your code and take a look at the larger picture. Firebug provides a view of network assets in the Net panel (Figure 10-3). This panel provides a visualization of the pauses between scripts and other assets, providing deeper insight into the effect the script is having on the loading of other files and on the page in general.

    通常,当遇到性能问题时,最好从代码中退出来,看看更大的图景。Firebug在网络面板中提供了一个网络资源视图(如图10-3)。此面板提供了脚本和其他资源的静态视图,可深入探查脚本对其它文件加载造成的影响和对页面造成的一般影响。

Figure 10-3. Firebug Net panel

图10-3  Firebug网络面板

 

    The colored bars next to each asset break the loading life cycle into component phases (DNS lookup, waiting for response, etc.). The first vertical line (which displays as blue) indicates when the page's DOMContentLoaded event has fired. This event signals that the page's DOM tree is parsed and ready. The second vertical line (red) indicates when the window's load event has fired, which means that the DOM is ready and all external assets have completed loading. This gives a sense as to how much time is spent parsing and executing versus page rendering.

    每个资源后面的彩条将加载过程分解为组件阶段(DNS察看,等待响应,等等)。第一条垂直线(显示为蓝色)指出页面的DOMContentLoaded事件发出的时间。此事件表明页面的DOM树已经解析并准备好了。第二条垂直线(红色)指出window的load事件发出的时间,它表示DOM已准备好并且所有外部资源已完成加载。这样就给出了一个场景,关于解析和运行以及页面渲染所花费的时间。

 

    As you can see in the figure, there are a number of scripts being downloaded. Based on the timeline, each script appears to be waiting for the previous script prior to starting the next request. The simplest optimization to improve loading performance is to reduce the number of requests, especially script and stylesheet requests, which can block other assets and page rendering. When possible, combine all scripts into a single file in order to minimize the total number of requests. This applies to stylesheets and images as well.

    正如你在图中看到的,下载了很多脚本。在时间线上,每个脚本看上去要等待前面的脚本首先启动下一个请求。提高加载性能的最简单的优化办法是减少请求数量,特别是脚本和样式表请求,它们会阻塞其它资源和页面渲染。如果可能的话,将所有脚本合并为一个文件,以减少总的请求数量。这种方法对样式表和图片同样有用。

 

Internet Explorer Developer Tools  IE开发人员工具

 

    As of version 8, Internet Explorer provides a development toolkit that includes a profiler. This toolkit is built into IE 8, so no additional download or installation is required. Like Firebug, the IE profiler includes function profiling and provides a detailed report that includes the number of calls, time spent, and other data points. It adds the ability to view the report as a call tree, profile native functions, and export the profile data. Although it lacks a network analyzer, the profiler can be supplemented with a generic tool such as Fiddler, which is outlined later in this chapter. See http://msdn.microsoft.com/en-us/library/dd565628(VS.85).aspx for more details.

    Internet Explorer 8提供了一个开发工具包,它包含一个分析器。此工具包内建于IE 8,所以不需要额外的下载和安装。像Firebug一样,IE分析器包括函数分析和细节报告,可以指出调用次数,花费时间,还有其它数据点。它能够以调用树形式察看报告,分析原生函数,并导出分析数据。虽然它没有网络分析器,但是此分析器可以增补一个通用工具注入Fiddler,它将在本章稍后部分介绍。更多详细信息参见http://msdn.microsoft.com/en-us/library/dd565628(VS.85).aspx

 

    IE 8's Profiler can be found with the Developer Tools (Tools → Developer Tools). After pressing the Start Profiling button, all subsequent JavaScript activity is monitored and profiled. Clicking Stop Profiling (same button, new label) stops the profiler and generates a new report. By default, F5 starts the profiler and Shift-F5 ends it.

    IE 8的性能分析器(译者注:简体中文版称作“探查器”)可以在开发人员工具中找到(工具菜单 → 开发人员工具)。在按下Start Profiling按钮(译者注:简体中文版称作“开始配置文件”)之后,所有后续的JavaScript活动都会被监视并分析。点击Stop Profiling(同一个按钮,只是上面的文字标签变了)(译者注:简体中文版称作“停止配置文件”)将停止分析器并生成一个新的报告。默认快捷键是F5启动分析器,Shift-F5停止它。

 

    The report provides both a flat function view of the time and duration of each call and a tree view showing the function call stack. The tree view allows you to walk through the call stack and identify slow code paths (see Figure 10-4). The IE profiler will use the variable name when no name is available for the function.

    报告显示了一个平面函数视图,包含每次调用的时间和持续时间。还有一个树状视图,显示了函数调用栈。树形视图使你可以遍历察看调用栈并定位出缓慢代码的路径(参见图10-4)。IE分析器将使用函数的变量名来显示匿名函数。

Figure 10-4. IE 8 Profiler call tree

图10-4  IE 8分析器的调用树

 

    The IE Profiler also provides insight into native JavaScript object methods. This allows you to profile native objects in addition to implementation code, and makes it possible to do things such as compare String::indexOf with RegExp::test for determining whether an HTML element's className property begins with a certain value:

    IE分析器还可以观察原生JavaScript对象方法。你可以添加调用代码来分析原生对象,那么就能够比较String::indexOf和RegExp::test,用于确定一个HTML元素的className属性是否具有特定值。

 

var count = 10000,
    element = document.createElement('div'),
    result, i, time;


element.className = 'foobar';


for (i = 0; i < count; i++) {
  result = /^foo/.test(element.className);
}


for (i = 0; i < count; i++) {
  result = element.className.search(/^foo/);
}


for (i = 0; i < count; i++) {
  result = (element.className.indexOf('foo') === 0);
}

    As seen in Figure 10-5, there appears to be a wide variation in time between these various approaches. Keep in mind that the average time of each call is zero. Native methods are generally the last place to look for optimizations, but this can be an interesting experiment when comparing approaches. Also keep in mind that with numbers this small, the results can be inconclusive due to rounding errors and system memory fluctuations.

    如图10-5所示,这些不同方法所用的时间差异很大。注意,每次调用的平均时间是零。原生函数通常是最后寻找优化的地方,但这是一个有趣的比较实验。同时请注意,由于这个数字很小,可能由于舍入误差和系统内存波动而无法得出确切结论。

Figure 10-5. Profile results for native methods

图10-5  原生方法的分析结果

 

    Although the IE Profiler does not currently offer a JavaScript API, it does have a console API with logging capabilities. This can be leveraged to port the console.time() and console.timeEnd() functions over from Firebug, allowing the same tests to run in IE.

    虽然IE分析器目前不提供JavaScript的API,但它有一个具有日志功能的控制台API。可以将console.time()和console.timeEnd()函数从Firebug上移植过来,从而在IE上进行同样的测试。


if (console && !console.time) {
  console._timers = {};
  console.time = function(name) {
    console._timers[name] = new Date();
  };
  console.timeEnd = function(name) {
    var time = new Date() - console._timers[name];
  console.info(name + ': ' + time + 'ms');
  };
}

 

Safari Web Inspector  Safari网页监察器

 

    Safari, as of version 4, provides a profiler in addition to other tools, including a network analyzer, as part of its bundled Web Inspector. Like the Internet Explorer Developer Tools, the Web Inspector profiles native functions and provides an expandable call tree. It also includes a Firebug-like console API with profiling functionality, and a Resource panel for network analysis.

    Safari 4提供了分析器等工具,包括网络分析器,它作为网页检查器的一部分。正如Internet Explorer开发人员工具那样,网页检查器可以分析原生函数并提供一个可以展开的调用树(视图)。它还包括一个类似Firebug具有分析功能的控制台API,网络分析器还具有一个资源面板。

 

    To access the Web Inspector, first make sure that the Develop menu is available. The Develop menu can be enabled by opening Preferences → Advanced and checking the "Show Develop menu in menu bar" box. The Web Inspector is then available under Develop → Show Web Inspector (or the keyboard shortcut Option-Command-I).

    要访问网页检查器,首先确定Develop菜单是否可用。可通过Preferences → Advanced菜单命令,选中“在菜单栏上显示开发菜单”。然后可以用Develop → Show Web Inspector打开网页检查器(键盘快捷命令是Option-Command-I)。

 

Profiles Panel  分析面板

 

    Clicking the Profile button brings up the Profile panel (Figure 10-6). Click the Enable Profiling button to enable the Profiles panel. To start profiling, click the Start Profiling button (the dark circle in the lower right). Click Stop Profiling (same button, now red) to stop the profile and show the report.

    点击Profile按钮打开分析面板(如图10-6)。点击Enable Profiling按钮启用分析面板。点击Start Profiling按钮开始分析(右下方的暗色圆圈)。点击Stop Profiling(同一个按钮,现在是公司)停止分析并便是报告。

Figure 10-6. Safari Web Inspector Profile panel

图10-6  Safari的网页检查器分析面板

 

    Safari has emulated Firebug's JavaScript API (console.profile(), console.time(), etc.) in order to start and stop profiling programmatically. The functionality is the same as Firebug's, allowing you to name reports and timings for better profile management.

    Safari模仿了Firebug的JavaScript API(console.profile(),console.time(),等等),可以用程序启动和停止分析功能。此功能与Firebug的完全相同,允许你对报告和计时进行命名以提供更好的分析管理。

 

    Safari provides both a Heavy (bottom-up) view of the profiled functions and a Tree (top-down) view of the call stack. The default Heavy view sorts the slowest functions first and allows traversal up the call stack, whereas the Tree view allows drilling from the top down into the execution path of the code from the outermost caller. Analyzing the call tree can help uncover more subtle performance issues related to how one function might be calling another.

    Safari提供了一个重视图(由下而上)用于函数分析,和一个树视图(由上而下)用于显示调用栈。默认的重视图将最慢的函数排在前面,并允许遍历调用栈,而树视图可从上至下地从最外层调用进入代码的运行路径。分析调用树有助于揭露与函数调用方法相关的性能问题。

 

    Safari has also added support for a property called displayName for profiling purposes. This provides a way to add names to anonymous functions that will be used in the report output. Consider the following function assigned to the variable foo:

    Safari还增加了一个名为displayName的属性专用于分析目的。它提供了一种为匿名函数在输出报告中添加名称的方法。考虑下面这个赋值给变量foo的函数:

 

var foo = function() {
  return 'foo!';
};
console.profile('Anonymous Function');
foo();
console.profileEnd();

    As shown in Figure 10-7, the resulting profile report is difficult to understand because of the lack of function names. Clicking on the URL to the right of the function shows the function in the context of the source code.

    如图10-7所示,因为缺少函数名,分析报告难以理解。点击函数右面的URL以源码方式显示出函数内容。

Figure 10-7. Web Inspector Profile panel showing anonymous function

图10-7  网页检查器的分析面板显示匿名函数

 

    Adding a displayName will make the report readable. This also allows for more descriptive names that are not limited to valid function names.

    添加一个displayName属性将使报告变得可读。可添加更具有描述意义的名字而不仅限于函数名。

 

var foo = function() {
  return 'foo!';
};
foo.displayName = 'I am foo';

    As shown in Figure 10-8, the displayName now replaces the anonymous function. However, this property is available only in Webkit-based browsers. It also requires refactoring of truly anonymous functions, which is not advised. As discussed earlier, adding the name inline is the simplest way to name anonymous functions, and this approach works with other profilers:

    如图10-8所示,displayName现在取代了匿名函数。但是,此属性仅适用于基于Webkit的浏览器。它还要求重构真正的匿名函数,所以不建议这么做。正如前面所讨论过的,添加内联名称是命名匿名函数最简单的方法,而且可以在其他分析器上工作。

 

var foo = function foo() {
  return 'foo!';
};

Figure 10-8. Web Inspector Profile panel showing displayName

图10-8  网页检查器的分析面板显示了displayName属性

 

Resources Panel  资源面板

 

    The Resources panel helps you better understand how Safari is loading and parsing scripts and other external assets. Like Firebug's Net panel, it provides a view of the resources, showing when a request was initiated and how long it took. Assets are conveniently color-coded to enhance readability. Web Inspector's Resources panel separates the size charting from time, minimizing the visual noise (see Figure 10-9).

    资源面板可帮助您更好地理解Safari加载和解析脚本以及其他外部资源的方式。就像Firebug的网络面板,它提供了一个资源视图,显示出一个发起的请求以及它持续了多长时间。资源以不同颜色显示以方便察看。网页检查器的资源面板将尺寸表与时间表分开,缩小了视觉上的干扰(如图10-9)。

Figure 10-9. Safari Resources panel

图10-9  Safari的资源面板

 

    Notice that unlike some browsers, Safari 4 is loading scripts in parallel and not blocking. Safari gets around the blocking requirement by ensuring that the scripts execute in the proper order. Keep in mind that this only applies to scripts initially embedded in HTML at load; dynamically added scripts block neither loading nor execution (see Chapter 1).

    请注意,不像某些浏览器那样,Safari 4能够并行加载脚本而不会互相阻塞。Safari绕过被阻塞的请求,还要确保脚本按照正确的顺序执行。请记住,这仅适用于HTML加载时嵌入的那些初始脚本,动态添加的脚本块不会被加载,也不会被运行(参见第一章)。

 

Chrome Developer Tools  Chrome开发人员工具

 

    Google has also provided a set of development tools for its Chrome browser, some of which are based on the WebKit/Safari Web Inspector. In addition to the Resources panel for monitoring network traffic, Chrome adds a Timeline view of all page and network events. Chrome includes the Web Inspector Profiles panel, and adds the ability to take "heap" snapshots of the current memory. As with Safari, Chrome profiles native functions and implements the Firebug Console API, including console.profile and console.time.

    Google也为它的Chrome浏览器提供了一套开发工具集,有一些基于WebKit/Safari网页检查器。除了监视网络流量的资源面板之外,Chrome为所有页面和网络事件添加了一个时间线视图。Chrome包含网页检查器的分析面板,增加了对当前“堆内存”的快照功能。正如Safari那样,Chrome能够分析原生函数并实现了Firebug的控制台API,包括console.profile和console.time。

 

    As shown in Figure 10-10, the Timeline panel provides an overview of all activities, categorized as either "Loading", "Scripting," or "Rendering". This enables developers to quickly focus on the slowest aspects of the system. Some events contain a subtree of other event rows, which can be expanded or hidden for more or less detail in the Records view.

    如图10-10所示,时间线面板提供了所有活动的概况,按类别分为“加载”,“脚本”,或“渲染”。这使得开发人员可以快速定位系统中速度最慢的部分。某些事件包含其他事件行的子树,在报告视图中可以展开或隐藏以显示更多或更少的细节。

Figure 10-10. Chrome Developer Tools Timeline panel

图10-10  Chrome开发者工具的时间线面板

 

    Clicking the eye icon on Chromes Profiles panel takes a snapshot of the current JavaScript memory heap (Figure 10-11). The results are grouped by constructor, and can be expanded to show each instance. Snapshots can be compared using the "Compared to Snapshot" option at the bottom of the Profiles panel. The +/- Count and Size columns show the differences between snapshots.

    点击Chrome分析面板上的眼睛图标,可获得当前JavaScript堆内存的快照(图10-11)。其结果按照构造器分组,可以展开察看每个实例。快照可使用性能面板底部的“比较快照”选项来进行比较。带+/-号的Count列和Size列显示出快照之间的差异。

Figure 10-11. Chrome Developer Tools JavaScript heap snapshot

图10-11  Chrome开发人员工具的JavaScript堆内存快照

 

Script Blocking  脚本阻塞

 

    Traditionally, browsers limit script requests to one at a time. This is done to manage dependencies between files. As long as a file that depends on another comes later in the source, it will be guaranteed to have its dependencies ready prior to execution. The gaps between scripts may indicate script blocking. Newer browsers such as Safari 4, IE 8, Firefox 3.5, and Chrome have addressed this by allowing parallel downloading of scripts but blocking execution, to ensure dependencies are ready. Although this allows the assets to download more quickly, page rendering is still blocked until all scripts have executed.

    传统上,浏览器每次只能发出一个脚本请求。这样做是为了管理文件之间的以来关系。只要一个文件依赖于另一个在源码中靠后的文件,它所依赖的文件将保证在它运行之前被准备好。脚本之间的差距表明脚本被阻塞了。新式浏览器诸如Safari 4,IE 8,Firefox 3.5,和Chrome解决这个问题的办法是允许并行下载,但阻塞式运行,以保证依赖体已经准备好了。虽然这使得资源下载更快,页面渲染仍旧会阻塞,直至所有脚本都被执行。

 

    Script blocking may be compounded by slow initialization in one or more files, which could be worthy of some profiling, and potentially optimizing or refactoring. The loading of scripts can slow or stop the rendering of the page, leaving the user waiting. Network analysis tools can help identify and optimize gaps in the loading of assets. Visualizing these gaps in the delivery of scripts gives an idea as to which scripts are slower to execute. Such scripts may be worth deferring until after the page has rendered, or possibly optimizing or refactoring to reduce the execution time.

    脚本阻塞将因为一个或多个文件初始化缓慢而变得更加严重,值得对它做某些类型的分析,并有可能优化或重构。脚本加载会减慢或停止页面渲染,造成用户等待。网络分析工具有助于找出并优化加载资源之间差距。以图形显示出传送脚本时的差异,可找出那些运行较慢的脚本。这些脚本也许应该推迟到页面渲染之后再加载,或者尽可能优化或重构以减少运行时间。

 

Page Speed

 

    Page Speed is a tool initially developed for internal use at Google and later released as a Firebug addon that, like Firebug's Net panel, provides information about the resources being loaded on a web page. However, in addition to load time and HTTP status, it shows the amount of time spent parsing and executing JavaScript, identifies deferrable scripts, and reports on functions that aren't being used. This is valuable information that can help identify areas for further investigation, optimization, and possible refactoring. Visit http://code.google.com/speed/page-speed/ for installation instructions and other product details.

    Page Speed最初是Google内部开发所使用的一个工具,后来作为Firebug插件发布,像Firebug的网络面板一样提供了关于页面资源加载的信息。然而,除了加载时间和HTTP状态,它还显示JavaScript解析和运行所花费的时间,指出造成延迟的脚本,并报告那些没有被使用的函数。这些有价值的信息可帮助确定进一步调查的方向,优化,以及可能的重构。访问http://code.google.com/speed/page-speed/关于安装及其他产品细节。

 

    The Profile Deferrable JavaScript option, available on the Page Speed panel, identifies files that can be deferred or broken up in order to deliver a smaller initial payload. Often, very little of the script running on a page is required to render the initial view. In Figure 10-12 you can see that a majority of the code being loaded is not used prior to the window's load event firing. Deferring code that isn't being used right away allows the initial page to load much faster. Scripts and other assets can then be selectively loaded later as needed.

    Page Speed面板上的分析延迟JavaScript选项,指出哪些文件可造成延迟或者可以拆分为一个较小的初始化载荷。通常,页面上运行的脚本极少需要渲染初始视图。在图10-12中您可以看到,大部分代码加载之后,不会在window发出load事件之前被用到。延迟(加载)这些不会被立刻用到的代码可使得初始化页面加载过程更快。如果需要的话,脚本和其它资源可以有选择地稍后加载。

Figure 10-12. Page Speed deferrable JavaScript summary

图10-12  Page Speed的延迟JavaScript总结

 

    Page Speed also adds a Page Speed Activity panel to Firebug. This panel is similar to Firebug's own Net panel, except that it provides more granular data about each request. This includes a breakdown of each script's life cycle, including parse and execution phases, giving a detailed account of the gaps between scripts. This can help identify areas where profiling and possible refactoring of the files are needed. As seen in the legend, Figure 10-13 shows the amount of time spent parsing the script in red and the time executing in blue. A long execution time may be worth looking into more closely with a profiler.

    Page Speed还为Firebug增加了一个页面速度活动面板。此面板类似于Firebug自己的网络面板,不过它为每个请求提供了更加精细的数据。其中包括每个脚本生命周期的统计分析——解析和运行阶段,给出了脚本之间时间差异的详细报告。这有助于分析特定区域并在需要的情况下重构这些文件。正如传说中的图10-13显示出红色的脚本解析时间和蓝色的运行时间。运行时间太长的脚本更需要我们用分析器深入研究。

Figure 10-13. Page Speed parse and execution times

图1-=13  Page Speed的解析和运行时间

 

    There may be significant time spent parsing and initializing scripts that are not being used until after the page has rendered. The Page Speed Activity panel can also provide a report on which functions were not called at all and which functions may be delayable, based on the time they were parsed versus the time they were first called (Figure 10-14).

    可能有大量时间花费在解析和初始化脚本上,而这些脚本在页面渲染之后还没有用到。页面速度动作面板还提供报告指出哪些函数从来没有被调用过,哪些函数可以延迟使用,基于它们的解析时间以及它们第一次被调用的时间(如图10-14)。

Figure 10-14. Reports for delayable and uncalled functions

图10-14  可延迟函数和未调用函数的报告

 

    These reports show the amount of time spent initializing the function that are either never called or that could be called later. Consider refactoring code to remove uncalled functions and to defer code that isn't needed during the initial render and setup phase.

    此报告显示了那些从未被调用过或者以后才会被调用的函数初始化所用的总时间。考虑重构代码删除那些未被调用的函数,并且延迟加载那些在初始渲染和设置阶段用不到的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值