Learn how to minify optimally your Javascript and CSS code using PHP

Minifying files can have a real world performance difference in your project, not about the performance of your code in the browser, but the speed at which the user receives it and the load of the server when the file needs to be served for a lot of simultaneous connections.

Whatever the intention you have with the implementation of a minifier in your server, as always, we recommend you to don't reinvent the wheel (don't build your own minifier with PHP) and use a library. If you want more reasons about why you should use a library, we recommend you to read this great article.

In this article you will learn how to minify your CSS and JS code with 3 different libraries.

1. Compress Javascript and CSS with Minify

If you're looking for a class that minifies both Javascript and CSS, then you can use the Minify package written by MatthiasMullie. The Minify package can be used either with Composer and with plain PHP Classes.

Installation with composer

Add the Minify package as a dependency to your project using the following command:

composer require matthiasmullie/minify

Or edit your composer.json, add the following line to your require and then execute composer install:

{
    "require": {
        "matthiasmullie/minify": "^1.3"
    }
}

And then you'll be able to use Minify.

Installation without composer

If you don't use composer, then the installation process could take a little bit longer. As first, download the repository as a .zip file from the repository here or simply clone it with Git:

git clone https://github.com/matthiasmullie/minify.git

This package has a dependency on Path Converter, therefore you need to clone this repository too (or download the .zip of the repository):

git clone https://github.com/matthiasmullie/path-converter.git

Note

Make sure that you leave the directory structure intact (the files in data/js should stay in the same location relative to src/JS.php) for both Minify and Path Converter.

Now, if you're not using composer, then you probably have a folder for the third party libraries, inside this folder you will paste (respectively: minify/src and path-converter/src) the content of the /src folder of every library within a folder with the library name.

Finally, include the required files of the libraries in the code where you want to use it using require_once:

<?php

// make sure to update the path to where you cloned the projects too
$path = '/path/to/third-party-libraries';
require_once $path . '/minify/src/Minify.php';
require_once $path . '/minify/src/CSS.php';
require_once $path . '/minify/src/JS.php';
require_once $path . '/minify/src/Exception.php';
require_once $path . '/minify/src/Exceptions/BasicException.php';
require_once $path . '/minify/src/Exceptions/FileImportException.php';
require_once $path . '/minify/src/Exceptions/IOException.php';
require_once $path . '/path-converter/src/ConverterInterface.php';
require_once $path . '/path-converter/src/Converter.php';

And you're ready to use Minify in your code.

Usage

In order to know how to minify Javascript with this library, you can checkout the following examples:

use MatthiasMullie\Minify;

$sourcePath = '/path/to/source/css/file.js';
$minifier = new Minify\JS($sourcePath);

// we can even add another file, they'll then be
// joined in 1 output file
$sourcePath2 = '/path/to/second/source/css/file.js';
$minifier->add($sourcePath2);

// or we can just add plain js
$js = 'var test = 1';
$minifier->add($js);

// save minified file to disk
$minifiedPath = '/path/to/minified/js/file.js';
$minifier->minify($minifiedPath);

// or just output the content
echo $minifier->minify();

And to minify CSS (it works in the same way to compress Javascript but with the CSS class) use the following code:

use MatthiasMullie\Minify;

$sourcePath = '/path/to/source/css/file.css';
$minifier = new Minify\CSS($sourcePath);

// we can even add another file, they'll then be
// joined in 1 output file
$sourcePath2 = '/path/to/second/source/css/file.css';
$minifier->add($sourcePath2);

// or we can just add plain CSS
$css = 'body { color: #000000; }';
$minifier->add($css);

// save minified file to disk
$minifiedPath = '/path/to/minified/css/file.css';
$minifier->minify($minifiedPath);

// or just output the content
echo $minifier->minify();

We recommend you to visit the repository to get more information about the methods here.

2. Compress Javascript with Squeeze

To compress Javascript code we recommend you to use Squeeze. Squeeze shrinks, compresses, minifies and mangles Javascript code. It's a single PHP class that has been developed, maintained and thoroughly tested since 2003 on major JavaScript frameworks (e.g. jQuery). JSqueeze operates on any parse error free JavaScript code, even when semi-colons are missing. In term of compression ratio, it compares to YUI Compressor and UglifyJS.

We recommend you Squeeze because it:

  • Removes comments and white spaces.
  • Renames every local vars, typically to a single character.
  • Keep Microsoft's conditional comments.
  • In order to maximise later HTTP compression (deflate, gzip), new variables names are choosen by considering closures, variables' frequency and characters' frequency.
  • Can rename also global vars, methods and properties, but only if they are marked special by some naming convention. Use JSqueeze::SPECIAL_VAR_PACKER to rename vars whose name begins with one or more $ or with a single _.
  • Renames also local/global vars found in strings, but only if they are marked special.
  • If you use with/eval then be careful.
  • Replaces false/true by !1/!0
  • Replaces new Array/Object by []/{}#
  • Merges consecutive var declarations with commas
  • Merges consecutive concatened strings
  • Can replace optional semi-colons by line feeds, thus facilitating output debugging.
  • Keep important comments marked with /*!...
  • Treats three semi-colons ;;; like single-line comments.
  • Fix special catch scope across browsers
  • Work around buggy-handling of named function expressions in IE<=8

Follow the installation of Squeeze:

With composer

To install Squeeze in your project, execute the following command:

composer require patchwork/jsqueeze

Or modify the composer.json file, add the following line in require and then execute composer install:

{
    "require": {
        "patchwork/jsqueeze": "~2.0"
    }
}

After the installation, you'll be able to minify code using Squeeze.

Without composer

If you don't use composer, you can easily use Squeeze by copying the JSQueeze.php class and including it in your project using require_once:

require_once 'JSqueeze.php';

Usage

The usage of Squeeze is pretty simple and can be achieved using only 1 method. This method is squeeze:

<?php


use Patchwork\JSqueeze;

$jz = new JSqueeze();

// Retrieve the content of a JS file
$fatJs = file_get_contents('myJavascript.js');

$minifiedJs = $jz->squeeze(
    $fatJs,
    true,   // $singleLine
    true,   // $keepImportantComments
    false   // $specialVarRx
);

As first parameter of the function, provide the Javascript code that needs to be minified.

The second parameter $singleLine allows you to decide if you want to keep the break line if a semicolon is found. Normally, we want that this value is always set to true.

The third parameter $keepImportantComments allows you to decide if you want /*! comments to be removed.

The fourth parameter $specialVarRx defines the regular expression of special variables names for global vars, methods, properties and in string substitution, set it to false if you don't want any.

3. Compress Javascript with JShrink

JShrink is a javascript minifier written in PHP. It’s designed to take large javascript files and remove the superflous bit, making the download faster. JShrink has some advantages over other libraries. Since it was written in native php, rather than ported, it has better performance. It has some extra features, like the ability to retain licensing data after shrinking other content.

With composer

To use JShrink in your project, execute the following command:

composer require tedivm/jshrink

Or edit your composer.json file and add the following require line and then execute composer install:

{
    "require": {
        "tedivm/jshrink": "~1.0"
    }
}

Without composer

If you want to use JShrink without composer, just include the Minifier.php class of the library using require_once:

require_once 'Minifier.php';

Usage

The usage of JShrink is pretty simple, the clas Minifier provides access to the static method minify. This method expects as first parameter the Javascript string to be minified and as second parameter an array with options (actually, there is only 1 option flaggedComments):

<?php

$js = file_get_contents("my-javascript-file.js");

// Basic (default) usage
$minifiedCode = \JShrink\Minifier::minify($js);

// Disable YUI style comment preservation.
$minifiedCode = \JShrink\Minifier::minify($js, array(
    'flaggedComments' => false
));

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors