Obviously, in complicated setups, you’ll have a lot of CSS and JavaScript files registered to pages, and this is a major drawback. The current best practice is to compress and combine all CSS files into a single file and do the same with JavaScript files. As a result, we serve just two files instead of the whole bunch. You probably already know all of this. It would be really cool to have the asset system in Yii do it for you implicitly, though currently, there is no such provision. Yii has, however, got the helper console command that you can use to simplify the process of compressing your assets and wiring them to your application. The most beautiful part is that you will not need to change any of your view files; all existing *Asset::register() calls can stay the same.

Although the documentation describes the full process of introducing combined assets to the Yii application, we repeat it here to bring a lot more detail to this really complex process.

The overall idea behind asset compiling in Yii is that you prepare a special asset bundle with just two files: one containing all of the compiled CSS and the other containing all of the compiled JavaScript. Then, you override the configuration for asset bundles using the components.assetManager.bundles setting (read about it in the documentation) telling Yii to use this special, newly-created asset bundle instead of all of the usual bundles.

The \yii\console\controllers\AssetController class, which provides you with the ./yii asset command, encapsulates and automates the procedure of asset compilation. It even deals with the issue of files referenced from the CSS code for you, which is really amazing.

Let’s see what we need to do to accomplish this. First, we remember the HTML structure we have when accessing a route at our application, for example /site/login. The following picture is a screenshot from Firebug in which we see the number of elements our UI consists of:

Minimizing the assets

You can see both Twitter Bootstraps and our own stylesheets inside the head element. At the bottom of the body element, there’s a whole bunch of script elements with various pieces of JavaScript UI. Our goal is to replace all CSS references with just one reference and all these script tags with just a single one.

We need the actual executables that will do the job of compressing the assets. Yii 2 uses the YUI compressor for CSS compression and the Google Closure compiler for JavaScript compression, available at http://yui.github.io/yuicompressor/ and https://developers.google.com/closure/compiler/, respectively.