Make javascript run faster

Source: Internet
Author: User
Tags file url php template

I found this "Serving JavaScript Fast" on vitamin, a web technology-based website. After reading this article, I learned a lot about it. So I came up with the idea of translation. I had a problem with this person. When I saw an interesting English article, I wanted to turn it over by myself (although the English level is poor ). I first checked on the Internet, and some blogs have talked about this article (I am not familiar with it). I have summarized the key points in "Web application optimization skills for developers of Flickr". there is also an extended "gossip about Flickr", but it seems that there is no full-text translation (this is good, it won't be busy for a long time to find it useless ). Then, I wrote a letter asking the author if he could. The author promised: "sure-I 'd love you to translate it", but asked me to give him a link address after turning it over. If you get the permission, you will have a bottom in your mind. First introduce the author. Cal Henderson, from London, lives in San Francisco, California. PHP, MySQL, and Perl experts, and are currently the flickr Architect (who has been yahoo since the acquisition of flickr), as well as a specialized consultant for vitamin (write some technical articles ).

Since he is an architect, he should use the technologies mentioned in this Article. Therefore, by referring to the article and comparing websites, there are indications that this is true. Although the speed of access to flickr in China is not flattering, the acceleration effect is unknown, but it seems that there have never been any problems with the use of n-plus css and javascript resources, and it also proves the effectiveness of these technologies.

After carefully reading the article, I still have a strong feeling: this old man is too easy to sell off. It is thorough enough to explain the facts in a sentence rather than three sentences, it's just a bit too @ # $ % ...... Forget it. How can I turn it over? Be loyal to the original work, or be tampered. After several days of hard work, I joined my colleague thincat to help me (I am very grateful to my younger brother) and finally completed the work ~).

Full Text Translation:

Make javascript run faster

By Cal Henderson

The next generation of web applications makes javascript and css usable. We will tell you how to make these applications fast and agile.

We have established an application called "Web 2.0" and implemented rich content and interaction. We expect css and javascript to play more important roles. To make the application clean, we need to improve the files that render the page and optimize its size and shape to ensure the best user experience-in practice, this means a combination: make the content as small as possible, download as fast as possible, and avoid unnecessary re-acquisition of unchanged resources.

The situation is a bit complicated because of the css and js files. Compared with images, the source code may be changed frequently. Once changed, the client needs to download it again to make the local cache invalid (the same is true for versions saved in other caches ). In this article, we will focus on how to make the user experience the fastest: including downloading the initial Page, downloading the subsequent page, and downloading resources as the application progresses and the content changes.

I always believe in this: developers should make things as simple as possible. Therefore, we prefer the methods that allow the system to automatically handle optimization problems. With only a little effort, we can build a rare environment: it makes development simple, has excellent terminal performance, and does not change the existing working method.

Hao freshman year

The old idea is that to optimize performance, you can merge multiple css and js files into a very small number of large files. It is better to combine a 50 K file with ten 5k js files. Although the total number of bytes in the Code remains unchanged, the overhead caused by multiple HTTP requests is avoided. Each request is created and eliminated on both the client and server, resulting in overhead of the request and response header, there are also more processes and thread resource consumption on the server side (there may be cpu time consumed for compressing content ).

(In addition to HTTP requests) concurrency is also important. By default, when persistent connections is used, ie and firefox only download two resources at the same time in the same domain name (recommended in section 8.1.4 of HTTP 1.1 specifications) (htmlor Note: You can change this default configuration by modifying the Registry and other methods ). This means that image resources cannot be downloaded while we are waiting to download two js files. That is to say, the user cannot see the image on the page during this period of time.

(Although merging files can solve the above two problems), this method has two disadvantages. First, package all resources together and force the user to download all resources at a time. If (rather than doing this) converts a large part of content into multiple files, the download overhead will be distributed to multiple pages, and the speed pressure in the session will be reduced (or some overhead will be completely avoided, it depends on the selected path ). If you download the initial Page slowly to make the subsequent page download faster, we will find that more users are not waiting to open the next page.

Second, if a single file system is used in an environment with frequent file changes, the client needs to re-download all css and js files each time the file is changed. If our application has a K merged js large file, any minor changes will force the client to digest the K again.

Decomposition path

(It seems inappropriate to merge large files .) The alternative solution is a compromise: the css and js resources are scattered into multiple sub-files, and the number of files is kept as small as possible by function. This solution also has a price. Although code distributed into logical chunks in the Development era can improve efficiency, files must be merged to improve performance during download. However, it is okay to add something to the build system (which turns the development code into a tool set for the product code for deployment.

For applications with different development and product environments, some simple technologies can be used to better manage the code. In the development environment, to make the code clear, the code can be divided into multiple logical parts (logical components ). You can create a simple function in Smarty (a php template language) to manage javascript downloads:

SMARTY:
{Insert_js files = "foo. js, bar. js, baz. js "}
PHP:
Function smarty_insert_js ($ args ){
Foreach (explode (',', $ args ['files']) as $ file ){
Echo "<script type =/" text/javascript/"SOURCE =/"/javascript/$ file/"> </script>/n ";
}
}
OUTPUT:
<Script type = "text/javascript" SOURCE = "/javascript/foo. js"> </script>

<Script type = "text/javascript" SOURCE = "/javascript/bar. js"> </script>
<Script type = "text/javascript" SOURCE = "/javascript/baz. js"> </script>

(Htmlor Note: wordpress will replace "src" with an unknown character, so only "SOURCE" is written here. Please replace it with your code, the same below)

That's simple. Then we run the build process command to merge the identified files. In this example, foo. js and bar. js are merged because they are almost always downloaded together. We can let the application configuration remember this and modify the template function to use it. (The Code is as follows :)

SMARTY:
{Insert_js files = "foo. js, bar. js, baz. js "}
PHP:
# Source file ing. After merging files in the build process, use this figure to find the js source file.
$ GLOBALS ['config'] ['js _ source_map '] = array (
'Foo. js' => 'foobar. js ',
'Bar. js' => 'foobar. js ',

'Baz. js' => 'baz. js ',
);
Function smarty_insert_js ($ args ){
If ($ GLOBALS ['config'] ['is _ dev_site ']) {
$ Files = explode (',', $ args ['files']);
} Else {
$ Files = array ();
Foreach (explode (',', $ args ['files']) as $ file ){
$ Files [$ GLOBALS ['config'] ['js _ source_map '] [$ file] ++;
}
$ Files = array_keys ($ files );
}
Foreach ($ files as $ file ){
Echo "<script type =/" text/javascript/"SOURCE =/"/javascript/$ file/"> </script>/n ";

}
}
OUTPUT:
<Script type = "text/javascript" SOURCE = "/javascript/foobar. js"> </script>
<Script type = "text/javascript" SOURCE = "/javascript/baz. js"> </script>

The source code in the template does not need to be changed to adapt to the development and product stages respectively. It helps us to keep the files scattered during development and merge the files when releasing them into products. If you want to go further, you can write the merge process in php and execute it using the same (merged file) configuration. In this way, there is only one configuration file to avoid synchronization problems. In order to do better, we can also analyze the probability that css and js files appear simultaneously on the page, to determine which files to merge is the most reasonable (files that appear almost always at the same time are the first choice for merging ).

For css, You can first create a master-slave relationship model, which is very useful. A primary style table controls all style sheets of an application. Multiple child style sheets control different application regions. In this way, most pages only need to download two css files, and one of them (the main style table) will be cached at the first request of the page.

For applications that do not have many css and js resources, this method may be slower than a single large file in the first request. However, if the number of files is small, you will find it faster, because the data size of each page is smaller. The download cost is distributed across different application regions, so the number of concurrent downloads is kept at a minimum, and the average download data volume on the page is also small.

Compression

When talking about resource compression, most people will immediately think of mod_gzip (but be careful that mod_gzip is actually a devil, at least a nightmare ). The principle is simple: when a browser requests a resource, it sends a header indicating that it can accept the content encoding. Like this:

Accept-Encoding: gzip, deflate

When the server encounters such a header request, it uses gzip or deflate to compress the content to the client and decompress it. This process reduces the data transmission volume and consumes the cpu time of the client and server. It is also unsatisfactory. However, mod_gzip works like this: first create a temporary file on the disk, then send it to the client, and finally delete the file. In high-capacity systems, due to disk io problems, the limit will soon be reached. To avoid this situation, you can use mod_deflate (only supported by apache 2 ). It adopts a more reasonable method: compress in the memory. For apache 1 users, a ram disk can be created to allow mod_gzip to write temporary files on it. Although there is no pure memory mode, it is not slower than writing files to the disk.

Even so, there is still a way to completely avoid the compression overhead, that is, pre-compress the relevant static resources. during download, mod_gzip provides the appropriate compression version. If compression is added to the build process, it is transparent. There are usually few files to be compressed (images do not need to be compressed, because they cannot reduce more sizes), only css and js files (and other uncompressed static content ).

The configuration option tells mod_gzip where to find the pre-compressed file.

Mod_gzip_can_negotiate Yes
Mod_gzip_static_suffix. gz
AddEncoding gzip. gz

The new version of mod_gzip (starting from 1.3.26.1a) can automatically pre-compress files after an additional configuration option is added. However, before that, you must ensure that apache has the correct permissions to create and overwrite compressed files.

Mod_gzip_update_static Yes

Unfortunately, things are not that simple. Some versions of Netscape 4 (especially 4.06-4.08) think they can interpret the Compressed Content (they send a header), but they cannot be decompressed correctly. Most other versions of Netscape 4 have various problems when downloading compressed content. So we need to test the proxy type on the server side (if it is Netscape 4, We Need To) to get them uncompressed versions. This is simple. Ie (Version 4-6) has some more interesting problems: When downloading compressed javascript, sometimes ie may incorrectly decompress the file or decompress the file halfway, then, the half files are displayed on the client. If your application depends heavily on javascript (htmlor Note: for example, ajax application), you must avoid sending compressed files to ie. In some cases, some older 5.x versions of ie can correctly receive compressed javascript, But they ignore the etag header of the file and do not cache it. (Thincat friendly reminder: Although compression is incompatible with Some browsers, the number of browsers that cannot be compressed is now very small, I think the compression caused by the browser is not normal. Can these outdated browsers be installed in popular windows or unix environments)

Since there are so many problems with gzip compression, we may wish to focus on the other side: do not change the file format compression. Many of these javascript compression scripts are available now. Most of them use a regular expression-driven statement set to reduce the size of the source code. They do a few things: Remove comments, compress spaces, and shorten private variable names and remove negligible syntaxes.

Unfortunately, most scripts do not work as well, either with a relatively low compression rate, or in some cases, code is messy (or both ). Due to incomplete understanding of the parsing tree, it is difficult for the compressors to distinguish a comment from a reference string that looks like a comment. Because of the mixed use of closed structures, it is not easy to use regular expressions to identify which variables are private, so some techniques that shorten the variable name will disrupt some closed code.

Fortunately, there is a compressed file to avoid these problems: the dojo compressed file (the ready-made version is here ). It uses rhino (mozilla's javascript Engine, implemented in java) to create a parsing tree and submit it to the file. It can reduce the size of the Code, with only a small cost: because it is compressed only once during build. Since compression is implemented in the build process, it is clear. (Since there is no problem with compression,) We can add spaces and comments as we like in the source code without worrying about the impact on the product code.

Compared with javascript, css file compression is simpler. Since the css syntax does not contain too many referenced strings (usually url paths and fonts), we can use regular expressions to kill spaces. (htmlor Note: This sentence is the best, haha ). If there is a reference string, we can always combine a string of spaces (because you do not need to search for multiple spaces and tabs in the url path and the body name ). In this case, a simple perl script is enough:

#! /Usr/bin/perl
My $ data = '';
Open F, $ ARGV [0] or die "Can't open source file: $! ";
$ Data. =$ _ while <F>;
Close F;
$ Data = ~ S! /*(.*?) */!! G; # Remove comments
$ Data = ~ S! S +! ! G; # compress Spaces
$ Data = ~ S !} !} /N! G; # add a line break after ending braces
$ Data = ~ S! /N $ !!; # Delete the last line feed
$ Data = ~ S! {! {! G; # Remove spaces after braces
$ Data = ~ S !; }!}! G; # Remove spaces before ending braces
Print $ data;

Then, you can pass a single css file to the script for compression. The command is as follows:

Perl compress. pl site.source.css> site.compress.css

After completing these simple text optimization work, we can reduce the amount of data transferred by up to 50% (this amount depends on your code format and may be more ). This provides a faster user experience. But what we really want to do is to avoid user requests as much as possible-unless necessary. Now the HTTP cache knowledge comes in handy.

Cache is a good thing

When a user agent (such as a browser) requests a resource from the server, it caches the server's response after the first request to avoid repeated identical requests. The length of cache time depends on two factors: the proxy configuration and the Cache control header of the server. All browsers have different configuration options and processing methods, but most of them cache at least one resource until the session ends (unless explicitly notified ).

To prevent the browser from caching pages with frequent changes, you may have sent headers without caching dynamic content. In php, the following two commands can be performed:

<? Php
Header ("Cache-Control: private ");
Header ("Cache-Control: no-cache", false );
?>

It sounds too simple? Indeed -- Some proxies (browsers) will ignore these headers in some environments. Make sure that documents are not cached in the browser:

<? Php
# Make it "invalid" in the past"
Header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT ");
# Always changed
Header ("Last-Modified:". gmdate ("D, d m y h: I: s"). "GMT ");
# HTTP and 1.1
Header ("Cache-Control: no-store, no-cache, must-revalidate ");
Header ("Cache-Control: post-check = 0, pre-check = 0", false );
# HTTP and 1.0
Header ("Pragma: no-cache ");
?>

In this way, the content we do not want to cache is enough. However, the browser should be encouraged to cache content that will not be changed during each request. The "If-Modified-Since" request header can do this. If the client sends an "If-Modified-Since" header in the request, apache (or other servers) will respond with status code 304 (not changed, tell the browser that the cache is up to date. Using this mechanism can avoid repeatedly sending files to the browser, but it still results in the consumption of an HTTP request. Well, think about it.

Similar to the If-Modified-Since mechanism, entity tag (entity tags) is used ). In apache, each response to a static file sends an "ETag" header, which contains a checksum generated by the file modification time, file size, and inode ). Before downloading an object, the browser sends a HEAD request to check the object's etag. ETag and If-Modified-Since have the same problem: the client still needs to execute an HTTP request to verify whether the local cache is valid.

In addition, if you use multiple servers to provide content, be careful to use if-modified-since and etags. In the two Server Load balancer environments, for A proxy (browser), A resource can be obtained from server A this time and from server B next time (htmlor note: the lvs load balancing system is a typical example ). This is good, and it is also the reason for using load balancing. However, if the two servers generate different etag or file modification date for the same file, the browser will be at a loss (each time it will be downloaded again ). By default, etag is generated by the inode Number of the file, while the inode numbers of files are different between multiple servers. You can use apache configuration options to turn it off:

FileETag MTime Size

With this option, apache only uses the file modification date and file size to determine etag. Unfortunately, this leads to another problem (the same can affect if-modified-since ). Since etag depends on the modification time, You Have To synchronize time. When you can upload files to multiple servers, the upload time difference is usually one to two seconds. In this way, the etag generated by the two servers is still different. Of course, we can also change the configuration so that the generation of etag depends only on the file size, but this means that if the file content changes but the size does not change, the etag will not change. This is not acceptable.

Cache is really a good thing

It seems that we are starting to solve the problem from the wrong direction. (Now the problem is) these possible cache policies cause one thing to happen repeatedly, that is, the client queries the server to check whether the local cache is up to date. If the server notifies the client when changing the file, the client will not know that its cache is up to date (until the next notification is received )? Unfortunately, tiangong is not doing well-(fact) is that the client sends a request to the server.

In fact, it is not clear. Before obtaining js or css files, the client sends a request to the server using the <script> or <link> flag, indicating which page to load these files. At this time, you can use the server response to notify the client of changes to these files. A bit vague. The details are as follows: if the css and js file content is changed, their file names will also be changed, you can tell the client that all the URLs are permanently cached-because each url is unique.

If we can determine that a resource will never change, we can issue some domineering cache headers (htmlor Note: This sentence is also very imposing ). In php, just two lines:

<? Php
Header ("Expires:". gmdate ("D, d m y h: I: s", time () + 315360000). "GMT ");
Header ("Cache-Control: max-age = 315360000 ");
?>

We told the browser that the content will expire in 10 years (about 315,360,000 seconds in 10 years, or more) and the browser will keep it for 10 years. Of course, it is very likely that php does not need to output css and js files (So header cannot be issued). This situation will be explained later.

Sometimes poor human resources

It is dangerous to manually change the file name when the file content is changed. If you change the file name, but the template does not point to it? If you have changed some templates, but haven't changed them? Suppose you have changed the Template but haven't changed the file name? What's worse, if you forget to change the name of the file or forget to change its reference? The best result is that the user can see the old but not the new content. The worst result is that the website cannot run because the file cannot be found. It sounds like this (modifying the url when modifying the file content) is a bad idea.

Fortunately, computers do this kind of thing-when a change happens, it needs to be done exactly, repeat and repeat (htmlor Note: Tomato eggs waiting ~) Boring work-always very good.

This process (modifying the File url) is not so painful, because we do not need to change the file name at all. The resource url and the file location on the disk do not need to be consistent. Using the mod_rewrite module of apache, you can establish simple rules to redirect a specified url to a specified file.

RewriteEngine on
RewriteRule ^/(. *.) v [0-9.] +. (css | js | gif | png | jpg) $/$1 $2 [L]

This rule matches any url with a specified extension that also contains "version" Information (version nugget). It redirects these URLs to a path without version information. As follows:

URL Path
/Images/foo.v2.gif->/images/foo.gif
/Css/main.v1.27.css->/css/main.css
/Javascript/md5.v6. js->/javascript/md5.js

With this rule, you can change the url without changing the file path (because the version number has changed ). Because the url is changed, the browser considers it as another resource (which will be downloaded again ). If you want to further develop, you can combine the previously mentioned script grouping function to generate a <script> tag list with a version number as needed.

Here, you may ask me, why not add a query string (such as/css/main.css) at the end of the url? V = 4 )? According to the HTTP cache specification, the user agent never caches URLs containing query strings. Although ie and firefox ignore this, opera and safari do not -- do not use query strings in URLs to ensure that all browsers cache your resources.

Now, you can change the url without moving the file. It is better if you can make the url update automatically. In a small product environment (if there is a large product environment, it is the development environment), you can easily implement this using the template function. Smarty is used here, and other template engines are also used.

SMARTY:
<Link xhref = "{version xsrc = '/css/group.css'}" rel = "stylesheet" type = "text/css"/>
PHP:
Function smarty_version ($ args ){
$ Stat = stat ($ GLOBALS ['config'] ['site _ root']. $ args ['src']);
$ Version = $ stat ['mtime'];
Echo preg_replace ('!. ([A-z] + ?) $! ', ". V $ version. $1", $ args ['src']);
}
OUTPUT:
<Link xhref = "/css/group.v1234567890.css" mce_href = "/css/group.v1234567890.css" rel = "stylesheet" type = "text/css"/>

For each linked resource file, we get its path on the disk and check its mtime (the last modification date and time of the file ), then insert the time into the url as the version number. This solution is good for low-traffic sites (with little overhead for their stat operations) or development environments, but it is not applicable to high-capacity environments-because each stat operation requires disk reading (resulting in increased server load ).

The solution is quite simple. In a large system, each resource has a version number, that is, the revision number of Version Control (you should have used version control, right ?). When we create a site for deployment, we can easily find the revision number of each file and write it in a static configuration file.

<? Php
$ GLOBALS ['config'] ['Resource _ version'] = array (
'/Images/foo.gif' => '2. 1 ',
'/Css/main.css' => '1. 27 ',
'/Javascript/md5.js' => '6. 123 ',
);
?>

When releasing a product, you can modify the template function to use the version number.

<? Php
Function smarty_version ($ args ){
If ($ GLOBALS ['config'] ['is _ dev_site ']) {
$ Stat = stat ($ GLOBALS ['config'] ['site _ root']. $ args ['src']);
$ Version = $ stat ['mtime'];
} Else {
$ Version = $ GLOBALS ['config'] ['Resource _ version'] [$ args ['src'];
}
Echo preg_replace ('!. ([A-z] + ?) $! ', ". V $ version. $1", $ args ['src']);
}
?>

In this way, you do not need to change the file name or remember which files have been changed. When a new version of the file is released, its url will be automatically updated.-Interesting? We can get it done.

Only Dongfeng

I mentioned earlier that cache headers that send very-long-period messages to static files cannot send cache headers easily without php output. Obviously, there are two solutions: php output or apache.

Php is out of the box. All we need to do is change the rewrite rules, point the static file to the php script, and use php to send the header before outputting the file content.

Apache:
RewriteRule ^/(. *.) v [0-9.] +. (css | js | gif | png | jpg) $/redir. php? Path = $1 $2 [L]
PHP:
Header ("Expires:". gmdate ("D, d m y h: I: s", time () + 315360000). "GMT ");
Header ("Cache-Control: max-age = 315360000 ");
# Ignore the path ".."
If (preg_match ('!..! ', $ _ GET [path]) {go_404 ();}
# Ensure that the path starts with a specified directory
If (! Preg_match ('! ^ (Javascript | css | images )! ', $ _ GET [path]) {go_404 ();}
# Does the file not exist?
If (! File_exists ($ _ GET [path]) {go_404 ();}
# Issuing a File header
$ Ext = array_pop (explode ('.', $ _ GET [path]);
Switch ($ ext ){
Case 'css ':
Header ("Content-type: text/css ");
Break;
Case 'js ':
Header ("Content-type: text/javascript ");
Break;
Case 'gif ':
Header ("Content-type: image/gif ");
Break;
Case 'jpg ':
Header ("Content-type: image/jpeg ");
Break;
Case 'png ':
Header ("Content-type: image/png ");
Break;
Default:

Header ("Content-type: text/plain ");
}
# Output file content
Echo implode ('', file ($ _ GET [path]);
Function go_404 (){
Header ("HTTP/1.0 404 File not found ");
Exit;
}

This solution is effective but not outstanding. (Because) php requires more memory and execution time than apache. In addition, we must be careful to prevent exploits that may be caused by passing forged values by the path parameter. To avoid these problems, use apache to directly send headers. The rewrite rule statement allows you to set the environment variable (environment variable) when the rule matches. After the given environment variable is set, the Header command can add the header. In combination with the following two statements, we bound the rewrite rule and header settings:

RewriteEngine on
RewriteRule ^ /(. *.) v [0-9.] +. (css | js | gif | png | jpg) $/$1 $2 [L, E = VERSIONED_FILE: 1]
Header add "Expires" "Mon, 28 Jul 2014 23:30:00 GMT" env = VERSIONED_FILE
Header add "Cache-Control" "max-age = 315360000" env = VERSIONED_FILE

Considering the apache execution sequence, you should add the rewrite rules to the master configuration file (httpd. conf) instead of the Directory configuration file (. htaccess. Otherwise, the header will be executed first (that makes no sense) before setting environment variables ). As for the header line, it can be placed in either of the two files. There is no difference.

Yan guan6 Road

(Htmlor Note: Thanks to tchaikov for telling me the meaning of "skinning rabbits", but I don't want to turn it over too formal. It should not be too outrageous .)

By combining the above technologies, we can build a flexible development environment and a fast and high-performance product environment. Of course, there is still some distance from the ultimate goal "Speed. There are many deeper technologies (such as separating static servo content and increasing concurrency with multiple domain names) worth our attention, including the methods we talked about (creating apache filters, modifying resource URLs, add version information. You can leave a comment to tell us the effective technologies and methods you are using.

(End)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.