[翻译]High Performance JavaScript(029)

Working Around Caching Issues  关于缓存问题

 

    Adequate cache control can really enhance the user experience, but it has a downside: when revving up your application, you want to make sure your users get the latest version of the static content. This is accomplished by renaming static resources whenever they change.

    充分利用缓存控制可真正提高用户体验,但它有一个缺点:当应用程序更新之后,你希望确保用户得到静态内容的最新版本。这通过对改动的静态资源进行重命名实现。

 

    Most often, developers add a version or a build number to filenames. Others like to append a checksum. Personally, I like to use a timestamp. This task can be automated using Ant. The following target takes care of renaming JavaScript files by appending a timestamp in the form of yyyyMMddhhmm:

    大多情况下,开发者向文件名中添加一个版本号或开发编号。有人喜欢追加一个校验和。个人而言,我更喜欢时间戳。此任务可用Ant自动完成。下面的目标体通过附加一个yyyyMMddhhmm格式的时间戳重名名JavaScript文件:

 

<target name="js.copy">
  <!-- Create the time stamp -->
  <tstamp/>
  <!-- Rename JavaScript files by appending a time stamp -->
  <copy todir="${build.dir}">
    <fileset dir="${src.dir}" includes="*.js"/>
    <globmapper from="*.js" to="*-${DSTAMP}${TSTAMP}.js"/>
  </copy>
</target>

 

Using a Content Delivery Network  使用内容传递网

 

    A content delivery network (CDN) is a network of computers distributed geographically across the Internet that is responsible for delivering content to end users. The primary reasons for using a CDN are reliability, scalability, and above all, performance. In fact, by serving content from the location closest to the user, CDNs are able to dramatically decrease network latency.

    内容传递网络(CDN)是按照地理分布的计算机网络,通过以太网负责向最终用户分发内容。使用CDN的主要原因是可靠性,可扩展性,但更主要的是性能。事实上,通过地理位置上最近的位置向用户提供服务,CDN可以极大地减少网络延迟。

 

    Some large companies maintain their own CDN, but it is generally cost effective to use a third-party CDN provider such as Akamai Technologies (http://www.akamai.com/) or Limelight Networks (http://www.limelightnetworks.com/).

    一些大公司维护它们自己的CDN,但通常使用第三方CDN更经济一些,如Akamai科技(http://www.akamai.com)或Limelight网络(http://www.limelightnetworkds.com)。

 

    Switching to a CDN is usually a fairly simple code change and has the potential to dramatically improve end-user response times.

    切换到CDN通常只需改变少量代码,并可能极大地提高最终用户响应速度。

 

    It is worth noting that the most popular JavaScript libraries are all accessible via a CDN. For example, the YUI library is served directly from the Yahoo! network (server name is yui.yahooapis.com, details available at http://developer.yahoo.com/yui/articles/hosting/), and jQuery, Dojo, Prototype, Script.aculo.us, MooTools, YUI, and other libraries are all available directly via Google’s CDN (server name is ajax.googleapis.com, details available at http://code.google.com/apis/ajaxlibs/).

    值得注意的是,最流行的JavaScript库都可以通过CDN访问。例如,YUI直接从Yahoo!网络获得(服务器名是yui.yahooapis.comhttp://developer.yahoo.com/yui/articles/hosting/)。jQuery,Dojo,Prototype,Script.aculo.us,MooTools,YUI,还有其他库都可以直接通过Google的CDN获得(服务器名是ajax.googleapis.comhttp://code.google.com/apis/ajaxlibs/)。

 

Deploying JavaScript Resources  部署JavaScript资源

 

    The deployment of JavaScript resources usually amounts to copying files to one or several remote hosts, and also sometimes to running a set of shell commands on those hosts, especially when using a CDN, to distribute the newly added files across the delivery network.

    部署JavaScript资源通常需要拷贝文件到一个或多个远程主机,有时在那些主机上运行一个shell命令集,特别当使用CDN时,通过传递网络分发最新添加的文件。

 

    Apache Ant gives you several options to copy files to remote servers. You could use the copy task to copy files to a locally mounted filesystem, or you could use the optional FTP or SCP tasks. My personal preference is to go directly to using the scp utility, which is available on all major platforms. Here is a very simple example demonstrating this:

    Apache Ant提供给你几个选项用于将文件复制到远程服务器上。你可以使用copy任务将文件复制到一个本地挂载的文件系统,或者使用FTP或SCP任务。我个人喜欢直接使用scp工具,因为所有主流平台都支持它。这是一个非常简单的例子:

 

<apply executable="scp" fail parallel="true">
  <fileset dir="${build.dir}" includes="*.js"/>
  <srcfile/>
  <arg line="${live.server}:/var/www/html/"/>
</apply>

    Finally, in order to execute shell commands on a remote host running the SSH daemon, you can use the optional SSHEXEC task or simply invoke the ssh utility directly, as demonstrated in the following example, to restart the Apache web server on a Unix host:

    最终,为了在远程主机上运行shell命令启动SSH服务,你可以使用SSHEXEC任务选项或简单地直接调用ssh工具,正如下面的例子中那样,在Unix主机上重启Apache网页服务:

 

<exec executable="ssh" fail>
  <arg line="${live.server}"/>
  <arg line="sudo service httpd restart"/>
</exec>

 

Agile JavaScript Build Process  灵巧的JavaScript开发过程

 

    Traditional build tools are great, but most web developers find them very cumbersome because it is necessary to manually compile the solution after every single code change. Instead, it's preferable to just have to refresh the browser window and skip the compilation step altogether. As a consequence, few web developers use the techniques outlined in this chapter, resulting in applications or websites that perform poorly. Thankfully, it is fairly simple to write a tool that combines all these advanced techniques, allowing web developers to work efficiently while still getting the most performance out of their application.

    传统开发工具很强大,但大多数网页开发人员嫌它们太麻烦,因为在每次修改之后都需要手工编译解决方案。开发人员更喜欢另一种方法,跳过整个编译步骤,直接刷新浏览器窗口。因此,几乎没有网页开发者使用本章之外的技术而导致应用程序或网站表现不佳。幸运的是,写一个综合上述优点的工具十分简单,它允许网页开发者在应用程序之外获得最佳性能。

 

    smasher is a PHP5 application based on an internal tool used by Yahoo! Search. It combines multiple JavaScript files, preprocesses them, and optionally minifies their content. It can be run from the command line, or during development to handle web requests and automatically combine resources on the fly. The source code can be found at http://github.com/jlecomte/smasher, and contains the following files:

    smasher是一个PHP5应用程序,基于Yahoo!搜索所使用的一个内部工具。它合并多个JavaScript文件,预处理它们,根据选项对它们内容进行紧凑处理。它可以从命令行运行,或者在开发过程中处理网页请求自动合并资源。源码可在http://github.com/jlecomte/smasher下载,包含以下文件:

 

smasher.php
    Core file  核心文件

 

smasher.xml
    Configuration file  配置文件

 

smasher
    Command-line wrapper  命令行封装

 

smasher_web.php
    Web server entry point  网页服务入口

 

    smasher requires an XML configuration file containing the definition of the groups of files it will combine, as well as some miscellaneous information about the system. Here is an example of what this file looks like:

    smasher需要一个XML配置文件包含要合并的文件组的定义,以及一些有关系统的信息。下面是这个文件的一个例子:

 

<?xml version="1.0" encoding="utf-8"?>
<smasher>
  <temp_dir>/tmp/</temp_dir>
  <root_dir>/home/jlecomte/smasher/files/</root_dir>
  <java_bin>/usr/bin/java</java_bin>
  <yuicompressor>/home/jlecomte/smasher/yuicompressor-2-4-2.jar</yuicompressor>


  <group id="yui-core">
    <file type="css" src="reset.css" />
    <file type="css" src="fonts.css" />
    <file type="js" src="yahoo.js" />
    <file type="js" src="dom.js" />
    <file type="js" src="event.js" />
  </group>


  <group id="another-group">
    <file type="js" src="foo.js" />
    <file type="js" src="bar.js" />
    <macro name="DEBUG" value="1" />
  </group>
  ...
</smasher>

    Each group element contains a set of JavaScript and/or CSS files. The root_dir top-level element contains the path to the directory where these files can be found. Optionally, group elements can also contain a list of preprocessing macro definitions.

    每一个group元素包含一个JavaScript或CSS文件集合。该root_dir顶层元素包含查找这些文件的路径。group元素还可通过选项来包含一个预处理宏定义列表。

 

    Once this configuration file has been saved, you can run smasher from the command line. If you run it without any of the required parameters, it will display some usage information before exiting. The following example shows how to combine, preprocess, and minify the core YUI JavaScript files:

    一旦这个配置文件保存下来,你就可以在命令行运行smasher。如果你不加任何参数运行它,它将在退出之前显示一些有用的信息。下面的例子演示了如何合并,预处理,和紧凑处理YUI核心JavaScript文件:

 

$ ./smasher -c smasher.xml -g yui-core -t js

 

    If all goes well, the output file can be found in the working directory, and is named after the group name (yui-core in this example) followed by a timestamp and the appropriate file extension (e.g., yui-core-200907191539.js).

    如果一切正常,可以在工作目录找到输出文件,它的名字以组名开头(这个例子中为yui-core)后面跟着一个时间戳和适当的文件扩展名(例如,yui-core-200907191539.js)。

 

    Similarly, you can use smasher to handle web requests during development by placing the file smasher_web.php somewhere under your web server document root and by using a URL similar to this one:

    同样,你可以使用smasher在开发过程中处理网页请求,将文件smasher_web.php放在你的网页服务根文档中,使用类似这样的URL:

 

http://<host>/smasher_web.php?conf=smasher.xml&group=yui-core&type=css&nominify

 

    By using different URLs for your JavaScript and CSS assets during development and in production, it is now possible to work efficiently while still getting the most performance out of the build process.

    在开发和产品中,为你的JavaScript和CSS资源使用不同的URL,现在它可以在开发过程之外获得最佳性能。

 

Summary  总结

 

    The build and deployment process can have a tremendous impact on the performance of a JavaScript-based application. The most important steps in this process are:

    开发和部署过程对基于JavaScript的应用程序可以产生巨大影响,最重要的几个步骤如下:

 

• Combining JavaScript files to reduce the number of HTTP requests

  合并JavaScript文件,减少HTTP请求的数量

 

• Minifying JavaScript files using the YUI Compressor

  使用YUI压缩器紧凑处理JavaScript文件

 

• Serving JavaScript files compressed (gzip encoding)

  以压缩形式提供JavaScript文件(gzip编码)

 

• Making JavaScript files cacheable by setting the appropriate HTTP response headers and work around caching issues by appending a timestamp to filenames

  通过设置HTTP响应报文头使JavaScript文件可缓存,通过向文件名附加时间戳解决缓存问题

 

• Using a Content Delivery Network to serve JavaScript files; not only will a CDN improve performance, it should also manage compression and caching for you

  使用内容传递网络(CDN)提供JavaScript文件,CDN不仅可以提高性能,它还可以为你管理压缩和缓存

 

    All these steps should be automated using publicly available build tools such as Apache Ant or using a custom build tool tailored to your specific needs. If you make the build process work for you, you will be able to greatly improve the performance of web applications or websites that require large amounts of JavaScript code.

    所有这些步骤应当自动完成,不论是使用公开的开发工具诸如Apache Ant,还是使用自定义的开发工具以实现特定需求。如果你使这些开发工具为你服务,你可以极大改善那些大量使用JavaScript代码的网页应用或网站的性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值