Merge and compress JavaScript and CSS files on the server

Source: Internet
Author: User
Tags php file web services browser cache

CSS Sprites and image ing are now everywhere, but this technology is not widely used because IE6 and IE7 do not support Data URI and performance problems. Currently, the number of JavaScript and CSS files in most web pages is the same as that in development. A small number of web pages are merged locally based on the actual situation. Many of these merge operations are performed manually, each new merge needs to be completed locally and uploaded to the server. This process is random and cumbersome, and the compression of the same file is similar. With the combination and compression of the server, we can make the file granularity as small as possible according to the development logic, and use the URL rules in the web page to automatically merge and compress files, this will be quite flexible and efficient.


YUI Combo Handler
On July 6, July 2008, YUI Team announced! CDN provides Combo Handler service for YUI JavaScript components. Combo Handler is Yahoo! Developed by an Apache module, it enables developers to easily merge JavaScript and CSS files through URLs, thus greatly reducing the number of file requests. For example, to use the Rich Text Editor component of YUI2 on a page, multiple JavaScript files need to be introduced. The common method is as follows:

<Script src = "http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/
Yahoo-dom-event.js> </script>
<Script src = "http://yui.yahooapis.com/2.8.0r4/build/container/
Container_core-min.js> </script>
<Script src = "http://yui.yahooapis.com/2.8.0r4/build/menu/menu-min.js"> </script>
<Script src = "http://yui.yahooapis.com/2.8.0r4/build/element/element-min.js"> </script>
<Script src = "http://yui.yahooapis.com/2.8.0r4/build/button/button-min.js"> </script>
<Script src = "http://yui.yahooapis.com/2.8.0r4/build/editor/editor-min.js"> </script>
After the Combo Handler service is used, the above code can be written as follows:

<Script src = "http://yui.yahooapis.com/combo?
2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js &
2.8.0r4/build/container/container_core-min.js &
2.8.0r4/create/menu/menu-min.js &
2.8.0r4/build/element/element-min.js &
2.8.0r4/build/button/button-min.js &
2.8.0r4/build/editor/editor-min.js "> </script> In addition to a slight reduction in code readability, the use of the Combo Handler service greatly reduces the number of HTTP requests, it also reduces the amount of URL code, which is crucial for Web performance optimization. Therefore, YUI Loader, the core component of YUI Loader, has the Combo Handling function, that is, when YUI Loader is used, by configuring the combine attribute, you can combine multiple JavaScript or CSS files to be loaded in the form of the Combo Handler service. In this case, you only need to support Combo Handler on the server of the static file. When combine is set to true in YUI, CDN uses Yahoo by default! CDN (http://yui.yahooapis.com), so there is no problem. This is one of the most fascinating aspects of YUI.

Unfortunately, the speed of http://yui.yahooapis.com in China is not good, originally Yahoo China provided http://cn.yui.yahooapis.com/, but not yet provided Combo Handler service, and for various reasons, its update stops after YUI 2.7.0. What's worse is Yahoo! Although the developed Apache module that supports Combo Handler is well documented to be open-source, it is still a private technology at least. To use it, you need to implement similar functions by yourself. Therefore, there are not many applications of similar technologies in China.

Minify
On Google Code, there is a PHP open-source project called Minify, which can merge, streamline, Gzip compression, and cache JavaScript and CSS files. Its file merging function is very similar to Combo Handler, but the URL syntax is slightly different. If Yahoo! If Minify is installed on CDN, the above Rich Text Editor code is written in the default Minify format:

<Script src = "http://yui.yahooapis.com/min/f=
2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js,
2.8.0r4/build/container/container_core-min.js,
2.8.0r4/build/menu/menu-min.js,
2.8.0r4/build/element/element-min.js,
2.8.0r4/build/button/button-min.js,
2.8.0r4/build/editor/editor-min.js "> </script> local use of Minify is very simple, just need Apache + PHP environment is OK:

1. Install Apache + PHP (Windows and Mac ).
2. Download the Minify source code, decompress it, and copy the min folder to the specified root directory, such as localhost. At this time, the URL is probably written as http: // localhost/min/f =...
3. Enable the Mod Rewrite module of Apache, create a. htaccess file in the min folder, and add the following Rewrite rules:
<IfModule mod_rewrite.c>
RewriteEngine on

# You may need RewriteBase on some servers
# If all the settings for enabling Mod Rewrite are still invalid, please try to enable the following sentence in the city:
# RewriteBase/min

# Rewrite URLs like "/min/f =..." to "/min /? F = ..."
RewriteRule ^ ([bfg] =. *) index. php? $1 [L, NE]
</IfModule> If the Mod Rewrite function is not enabled, the Minify URL is similar to http: // localhost/min/index. php? F = ..., This is not conducive to the cache of the client and the intermediate server, and the URL after Mod Rewrite is enabled is similar to http: // localhost/min/f = ..., It not only solves the preceding problems, but is shorter.

4. Configure Minify to edit the min/config. Php file.
$ Min_enableBuilder = true;
// You can use http: // dwn/min/builder/for local use. Set this parameter to false for external use.

// $ Min_cachePath = 'C: \ WINDOWS \ Temp ';
// $ Min_cachePath = '/tmp ';
// $ Min_cachePath = preg_replace ('/^ \ d +;/', '', session_save_path ());
// Select one. Remove the comment and set the temporary cache directory, which can reduce program operations and improve performance.

$ Min_serveOptions ['maxage'] = 1800;
// Set the browser cache time. It is recommended that this time be set as long as possible to improve performance, for example, 315360000
// If you need to update a static file without changing the URL, you can use a timestamp-like method,
// For example, http: // localhost/min/f = example/example.css&20100601.css
// We recommend that you use version number management for static files. You need to upgrade the version number for each modification so that no timestamp is required,
// For example, http: // localhost/min/f = example/example_1_0_1.css

$ Min_serveOptions ['minapp'] ['maxfiles'] = 10;
// Parameter f obtains the number of parameters, that is, the number of merged files. This quantity can be increased, for example, 50,
// Of course, you may encounter the URL maximum value problem, which will be explained later

$ Min_documentRoot = '';
// $ Min_documentRoot = substr (_ FILE __, 0, strlen (_ FILE _)-15 );
// $ Min_documentRoot = $ _ SERVER ['subdomain _ DOCUMENT_ROOT '];
// When $ min_documentRoot is empty, its value is $ _ SERVER ['document _ root'],
// But the merged file is not under $ _ SERVER ['document _ root'], which causes error 400,
// At this time, 2nd rows or 3rd rows can be enabled.

5. Use Minify
For example, there are two JavaScript files: http: // localhost/example/. js, http: // localhost/example/B. js, the merged URL using Minify is http: // localhost/min/f =/example/. js,/example/B. js. You can directly put this URL on the page.

In fact, Minify not only implements the merge function, but also compresses the file by default while merging. If you compress the file locally, for example, using YUI Compressor, in the config. in php, perform the following settings to cancel Minify compression to improve performance:

$ Min_serveOptions ['minifiers'] ['application/x-javascript '] = '';
$ Min_serveOptions ['minifiers'] ['text/css '] = '';
If the server supports Java, you can also configure Minify to compress JavaScript and CSS files using YUI Compressor.

Directly merge and compress on the server, which is flexible and greatly reduces the deployment process of front-end development results. For more configurations, see Minify CookBook and Wiki.

Tips: Minify uses the New BSD License, which means that the user can use the code almost freely. The BSD protocol encourages code sharing, but it must respect the copyright of the code author. BSD is a friendly protocol for business integration because it allows users to modify and re-release code, and also allows users to use or develop commercial software release and sales on BSD code. Many companies prefer the BSD protocol when selecting open-source products, because they have full control over these third-party code and can modify or perform secondary development as necessary. For more Chinese information, see BSD protocol.

Use Minify in YUI3
In YUI2, the merging mechanism only supports files of the library. Custom files are loaded separately. Since YUI3, the module becomes smaller, which leads to the longer URL when merging, but the maximum URL in IE is 2083, and the default maximum URL in Apache is 8192, therefore, when the URL exceeds the maximum value in the corresponding browser, YUI3 automatically splits the URL into multiple merged URLs based on the browser's judgment, and provides maxURLLength to set the maximum value. From YUI3.1.0, not only supports the merging of custom files, but also supports the use of multiple CDN to provide the merging service, that is, the YUI component can use the http://yui.yahooapis.com of this CDN, other files use CDN that supports merging, which is very practical, convenient, and flexible. This is illustrated by using Minify in YUI3.

Because the default yui url merging format is different from that of Minify, you need to use regular replacement to implement Minify URL merging in YUI instantiation. However, this method is not flexible, it is risky, unfriendly, and inefficient. The simple method is to directly modify the source code of YUI 3. For example, Minify is used in the modified YUI3. Meanwhile, YUI 3. 1. * The version has a bug, that is, when JavaScript and CSS are merged simultaneously, an & symbol is added at the end of the shorter URL. For example, in YUI3, Minify is used:

Http://yui.yahooapis.com/combo? 3.1.1/build/widget/assets/skins/sam/widget.css &
3.1.1/build/console/assets/skins/sam/console.css &

In future (such as IE6), there is a risk that resolution cannot be performed and the cache may be affected in some specific situations. However, when the modified YUI is used, the merged URL is like/min/B = yui & f = 3.1.1/tabview/assets/skins/sam/tabview.css, and a bug occurs. This is a small bug for YUI Combo Handler, so YUI3 sets this bug to P5. However, when we transform YUI3 to better support Minify, we also need to solve this problem. For the specific solution, see the example to use Minify in the modified YUI3.

Use Minify on CDN
CDN stands for Content Delivery Network (CDN. The most common application is to deploy static resources to the nearest edge of users through servers located in different geographic locations, which can effectively solve the speed and performance problems of a large number of static resources in Web services. Because the implementation cost is relatively high, in actual applications, large companies generally set up their own CDN, while small companies can only rent third-party CDN, however, either of the two methods will not affect the implementation of merge and compression programs on the server. Generally, static resources are not directly uploaded to CDN, but are first uploaded to a backend server. Then, the front-end Cache servers of CDN in various regions are requested as needed. The Combo Handler of yui cdn is deployed on its backend server, as should Minify. A simple illustration is as follows:


When a resource request is sent to CDN, CDN first checks whether the local resource exists. If yes, CDN directly returns the resource. If not, it requests the background server, the backend server processes the resource URL and returns the resource to CDN. Then, CDN stores the resource. When this resource is requested again, no backend server needs to be requested. Therefore, although merging, especially compressing JavaScript and CSS files, takes time, in addition, for the first time, we basically access it by ourselves (we can create a program to automatically perform an access, in fact, we can also use this method for image optimization), so it is basically safe. This is the merge JavaScript and CSS solution currently implemented in koubei.com.

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.