Overview

A small plugin that simply wraps YUI Compressor so you can compress CSS. It removes spaces, newlines, etc. This leads to faster load time for your webpages.

Note that this plugin only provides the CSS compression feature of YUI Compressor, not its ability to also compress Javascript. The reason is that YUI Compressor is not up to date in regard to Javascript... To optimize Javascript, use the Spincast JS Closure Compiler plugin!

Usage

You inject and use the SpincastCssYuiCompressorManager component to minify your CSS.

Let's say you have a dynamic resource route that serves your CSS files dynamically:

router.dir("/publicdyn/css/*{relativePath}")
      .pathRelative("/publicdyn/css")
      .handle(publicResourcesController::dynCss);

In the "dynCss(...)" handler, you would get the raw content of the CSS file and tweak it using the SpincastCssYuiCompressorManager component before sending the result:

File cssFile = //... get the CSS file

String rawCssContent = FileUtils.readFileToString(cssFile, "UTF-8");

String cssMinified = getSpincastCssYuiCompressorManager().minify(rawCssContent);

context.response().sendCharacters(cssMinified, "text/css");

Explanation :

  • 1 : We get the CSS file using the "relativePath" path parameter taken from the request. We make sure we validate this user input properly!
  • 3 : We get the raw CSS content.
  • 5 : We call the minify(...) method.
  • 7 : We send the minified CSS, using the proper content-type. Since this is a dynamic resource route, the result will be cached and it is this cached version that will be served on next requests!

SpincastCssYuiCompressorManager methods
The main methods provided by SpincastCssYuiCompressorManager are:
  • String minify(String cssContent)

    Run YUI Compressor on the specified CSS content, as a String. Return the compressed CSS.

  • void minify(File cssFile)

    Run YUI Compressor on the specified CSS file. The file will be modified and will contain the compressed CSS.

There is one extra option available on both methods: lineBreakPos. Here is the documentation about this option, taken directly from YUI Compressor documentation (search for "--line-break"):

"Some source control tools don't like files containing lines longer than, say 8000 characters. The linebreak option is used in that case to split long lines after a specific column. It can also be used to make the code more readable, easier to debug (especially with the MS Script Debugger) Specify 0 to get a line break after each semi-colon in JavaScript, and after each rule in CSS."

Pebble function to easily bundle multiple CSS files
If you are using Pebble, the default Templating Engine, a function is provided by this plugin to bundle multiple CSS files together directly from an HTML template.

Let's say your HTML template includes those .css files:


<link rel="stylesheet" href="/public/css/bootstrap.min.css">
<link rel="stylesheet" href="/public/css/anotherLibrary.css">
<link rel="stylesheet" href="/publicdyn/css/{{spincast.cacheBuster}}main.css">

You could convert those separate files to a single compressed bundle, so an unique and fast request is required from the client!

To do so, you use the cssBundle(...) Pebble function which is provided when this plugin is installed:


{{ cssBundle('/public/css/bootstrap.min.css',
             '/public/css/anotherLibrary.css',
             '/publicdyn/css/main.css') }}

This function will concatenate all the specified CSS files, will compress them using the YUI Compressor and will output a resulting "<link>" element pointing to the bundle:


<link rel="stylesheet" href="/spincast/plugins/cssyuicompressor/cssbundles/resultingBundle.css">

The parameters accepted by the cssBundle(...) function are:

  • First, the paths to the CSS files to bundle. Those paths must be absolute (they must start with a "/").
  • "--line-break-pos" followed by the value to use, "10" for example. There is an explanation of this option in the previous section.
  • "--spincast-no-cache-busting": when this flag is specified, no cache busting code will be added to the resulting bundle path.

The two supported options must be specified after the paths to the CSS files to bundle.

Here is an example of using cssBundle(...) with those options:


{{ cssBundle('/public/css/bootstrap.min.css',
             '/public/css/anotherLibrary.css',
             '/publicdyn/css/main.css',
             '--line-break-pos', '10',
             '--spincast-no-cache-busting') }}

Behind the scene, calling cssBundle(...) will not only generate the bundle, but will also automatically add the associated route to your router!

The resulting bundle will be cached (it will only be generated on the very first request), will be served with caching HTTP headers and will contain a cache busting code (except if the "--spincast-no-cache-busting" flag is used).

During development, you probably want to disable the bundling so changes made to the CSS files are available immediately (no cache). There is a configuration for that!

Don't forget to remove any "{{spincast.cacheBuster}}" tag when you move a regular .css file to a cssBundle(...) function!

Note that the content of the CSS files to bundle together will be retrieved using HTTP requests! This allows you to use dynamic resources to generate those files, if required.

Bundling multiple files may take a couple of seconds... If you want to prevent the first request made to this bundle to be slow, you can pre-generate the bundle when your application starts. Here is an example where we do this, for this very website.

If, for some reason, you want to change the output made by cssBundle(...), you can extend SpincastCssYuiCompressorPebbleExtensionDefault, override the "bundlingOutput(String path)" function and bind your implementation to the SpincastCssYuiCompressorPebbleExtension interface in the Guice context.

Configurations

You can bind a custom implementation of SpincastCssYuiCompressorConfig to tweak global configurations. This implementation can extend SpincastCssYuiCompressorConfigDefault as a base class.

  • String getCssBundlePebbleFunctionName()

    The name to give to the Pebble function provided by this plugin to bundle multiple CSS files together. It is the name you are going to use in your HTML file to call the function.

    Defaults to "cssBundle".

  • String getCssBundlesUrlPath()

    The base URL path where the CSS bundles will be served from. The path returned by the cssBundle() Pebble function will start with this base path.

    Defaults to "/spincast/plugins/cssyuicompressor/cssbundles".

  • File getCssBundlesDir()

    The directory where the cssBundle() Pebble function will save the generated CSS bundles.

    Defaults to "[WRITABLE_DIR]/spincast/plugins/cssyuicompressor/cssbundles".

  • boolean isCssBundlesIgnoreSslCertificateErrors()

    When the cssBundle() Pebble function retrieves the files to be bundled together, should SSL certificate errors be ignored? Setting this to true is useful during testing, on a development environment where a self-signed certificate may be used.

    Defaults to true if isDevelopmentMode() or isTestingMode() is true .

  • boolean isCssBundlesDisabled()

    When this is true, the cssBundle() Pebble function will not bundle the specified files together. The files will be served as usual, each with their own "<link>" tag.

    This is useful during development, when you don't want any cache and want changes to the files to be immediately available!

    Defaults to true if isDevelopmentMode() is true .

Dependencies

This plugin depends on the Spincast HTTP Client plugin which is not provided by default by the spincast-default artifact.

It also uses Spincast Pebble plugin which is included in the spincast-default artifact.

Those plugins will be automatically installed. Note that it is always a good idea to read the documentation of the automatically installed plugins though!

Installation

1. Add this Maven artifact to your project:

<dependency>
    <groupId>org.spincast</groupId>
    <artifactId>spincast-plugins-css-yuicompressor</artifactId>
    <version>1.14.1</version>
</dependency>

2. Add an instance of the SpincastCssYuiCompressorPlugin plugin to your Spincast Bootstrapper:


Spincast.configure()
        .plugin(new SpincastCssYuiCompressorPlugin())
        // ...