My favorites | Sign in
Project Logo
                
Search
for
Updated Jul 02 (3 days ago) by st...@mrclay.org
Labels: Phase-Deploy, Featured
UserGuide  
Your friendly guide to installing and using Minify.

If this page doesn't help, please post a question on our Google group.

Installing Minify for the first time

Download the latest Minify and unzip the files to a new "minify" directory.

Copy the "min" folder directly into your DOCUMENT_ROOT.

Done!

(Optional) See TestingMinify if you'd like to run unit tests.

Upgrading Minify from 2.1.x

See the Upgrade Guide

Usage

Browse to http://example.com/min/

The Minify URI Builder will help you create URIs you can use to minify existing files on your site. You can see screenshots and get a feel for this process from this walkthrough on mrclay.org

Configuration

Most configuration options are located in min/config.php. To set up groups of files to minify, this can specified in min/groupsConfig.php (The builder application will help with this).

Problems?

See CommonProblems and Debugging

Customized Sources / Options for Specific Files

In groupsConfig.php, you may use a Minify_Source object in place of a file path. This will allow you to set the exact function used to process the source, specify an option to be sent to the processing function, or even create a source that's not based on a static file. Here are a few examples:

Custom functions for files

// in groupsConfig.php:

function myMinifier($a) {return trim($a);}

return array(
    'js' => array(
        new Minify_Source(array(
            'filepath' => '//js/file1.js',
            'minifier' => ''  // don't minify this
        )),
        new Minify_Source(array(
            'filepath' => '//js/file2.js',
            'minifier' => 'myMinifier' // run myMinifier() on content
        )),
        '//js/site.js' // default JSMin minification
    )
);

Previous Releases

The following info applies only to the Minify 2.0 releases. Most users will not need to do any of this as of version 2.1.

Using the Groups controller

We're going to build a small PHP file that calls Minify::serve(), turning it into an HTTP server for our Javascript and CSS.

1. Place the following code in a file "min.php" in your root web directory.

<?php

// Prepends include_path. You could alternately do this via .htaccess or php.ini
set_include_path( 
    '/full/path/to/minify/lib'
    . PATH_SEPARATOR . get_include_path()
);

require 'Minify.php';
Minify::setCache(); // in 2.0 was "useServerCache"
Minify::serve('Groups', array(
    'groups' => array()
));

2. Open a non-IE/win web browser to http://example.com/min.php/ (IE/win will not display Javascript files directly.)

You should see "HTTP/1.0 400 Bad Request". Minify is working, let's give it something to serve.

Terminology: From here on I'll use "minify URI" to mean a URI that points to a Minify server, like "min.php/" in our example.

3. Note the file paths of a few Javascript files you'd like to serve together. If they're in the same webroot as your minifying script, we can substitue "//" for the DOCUMENT_ROOT.

E.g.: '//js/jQuery.js' is a shortcut for "{$_SERVER['DOCUMENT_ROOT']}/js/jQuery.js".

Note: Use file paths, not HTTP URIs. /file.js would result in PHP looking for file.js in the root directory of a Unix-ish filesystem.

To specify a file on a different virtual host, don't use http://example.com/file.js, instead give its path from root: /home/user/example.com/file.js.

4. Add them to the 'groups' array inside the Minify::serve() call, like this:

Minify::serve('Groups', array(
    'groups' => array(
        'js1' => array('//js/yourFile1.js', '//js/yourFile2.js')
    )
));

5. Browse to http://example.com/min.php/js1

After a brief delay (on the first request PHP has to compress the files), you'll receive a single minified Javascript file containing the code of "yourFile1.js" and "yourFile2.js". The file will also be sent with deflate or gzip encoding, depending on your browser.

6. Now you can use "/min.php/js1" as the src attribute for (X)HTML SCRIPT elements.

Serving more combinations of files, including CSS

You can add more elements to the "groups" array to serve more files. E.g.:

Minify::serve('Groups', array(
    'groups' => array(
        'js1' => array('//js/yourFile1.js', '//js/yourFile2.js')
        ,'js2' => array('//js/yourFile1.js', '//js/yourFile3.js')
        ,'jQuery' => array('//js/jquery-1.2.6.js')
        ,'css' => array('//css/layout.css', '//css/fonts.css')
    )
));

Now you can also use these URLs:

Sending far future Expires headers

By default Minify enables conditional GETs for client-side caching, but in this model the browser has to continuously check back with the server to revalidate its cache. A better method is to send far future Expires headers and change the URL when the file changes. As long as you generate your HTML with PHP, Minify makes it easy to do this.

1. Move the 'groups' configuration array into a separate file "groupsConfig.php":

<?php
// configures both Minify::serve() and Minify_Build
return array(
    'js1' => array('//js/yourFile1.js', '//js/yourFile2.js')
    ,'js2' => array('//js/yourFile1.js', '//js/yourFile3.js')
    ,'jQuery' => array('//js/jquery-1.2.6.js')
    ,'css' => array('//css/layout.css', '//css/fonts.css')
);

2. Adjust "min.php" to use this file:

Minify::serve('Groups', array(
    'groups' => (require '_groupsConfig.php')
));

3. In your HTML-generating script, create Minify_Build objects for each minify URI you're going to use, and, to each, apply the uri() method:

require 'Minify/Build.php';
$_gc = (require "_groupsConfig.php");
$js1Build = new Minify_Build($_gc['js1']);
$cssBuild = new Minify_Build($_gc['css']);

echo "<link rel='stylesheet' type='text/css' href='" . $cssBuild->uri('/min.php/css') . "' />";
/* ... */
echo "<script type='text/javascript' src='" . $js1Build->uri('/min.php/js1') . "'></script>";

5. Open the (X)HTML page in your browser. The Javascript and CSS should "work".

6. View source. The minify URIs should look like: "/min.php/js1?##########" (a unix timestamp)

7. Now that our URI's are synched with source file changes, we can safely send Expires headers. In "min.php":

Minify::serve('Groups', array(
    'groups' => (require '_groupsConfig.php')
    ,'maxAge' => 31536000 // 1 yr
    // in 2.0 was 'setExpires' => $_SERVER['REQUEST_TIME'] + 31536000
));

Now "min.php" will serve files with Expires headers, causing the browser to always retrieve them from cache (until the expiration date).

When you make a change to any of your source Javascript/CSS files, your HTML file will have a different querystring appended to the minify URIs, causing the browser to download it as a new URL, and Minify will automatically rebuild its cache files on the server.

Fixing URIs in CSS files (not required as of 2.1)

If you serve CSS with Minify you may notice your relative URIs in your CSS no longer point to the right places. To fix this, serve() can be pass an option to the CSS minifier that will prepend a string to all relative URIs. E.g.:

$serveOptions = array(
    'groups' => (require '_groupsConfig.php')
    ,'maxAge' => 31536000 // 1 yr
    // in 2.0 was 'setExpires' => $_SERVER['REQUEST_TIME'] + 31536000
);
// pass the 'prependRelativePath' to the CSS minifier:
$serveOptions['minifierOptions'][Minify::TYPE_CSS]['prependRelativePath'] = '/css/';
Minify::serve('Groups', $serveOptions);

Note: Before 2.0.2b replace ['minifierOptions'] with ['perType'].

Note: In version 2.1, this section will be unneeded as relative URIs are automatically fixed for you.

Notes


Comment by shariff.yulop, Sep 25, 2008

hi guys, i have configured the minify to work in my server .. my question is how to i check whether the files are caching or not ...

any suggestions ...

Comment by st...@mrclay.org, Sep 26, 2008

I suggest you always set $min_cachePath in /min/config.php. That way you know where the files are stored and can check them. Without that set, they may be in /tmp or several other directories depending on your OS.

Comment by deadpan110, Oct 01, 2008

Using .htaccess and RewriteRule? for Minify

I used the following within .htaccess to minify all .js and .css on my WordPress? MU site:

# .htaccess

RewriteEngine On
RewriteBase /
RewriteRule ^(.*\.(css|js))$ min/index.php?f=$1&debug=0 [L,NC]

# Note &debug=0 is not needed but I set it to 1 when needed
# (when $min_allowDebugFlag = true; is set within config.php)

I found this works great as I used this method in minify v1.0 but appears to break css background images.

/*wp-content/themes/mytheme/style.css*/

#someid {
    background: #6E6A66 url('pics/mygif.gif') repeat-x top;
}

becomes (According to my Firebug output)

This is fixed by using a previous mentioned option within config.php and switching the css URI rewrite option off.

$min_serveOptions['rewriteCssUris'] = false;

I hope this helps anyone attempting to do the same.

Comment by jasondaly, Oct 07, 2008

I am interested in a way to explicitly reference a group name to serve programatically, not pulling from the querystring. I have a self-built MVC framework, and have put the following code in a a method for one of my controllers

(From my <Controller_Proxy> class)

public function serve(){
  Minify::setCache();
  Minify::serve('Groups', array('groups' => $include_script_groups,
                                'maxAge' => 31536000));
}

as mentioned in the userguide, but my URL pattern (already using mod_rewrite) is

/controllerName/actionName/param1/param2/...

I would like to pass something like

/proxy/serve/core_css

but would like to know an option to pass to tell Minify to serve the 'core_css' group.

Comment by st...@mrclay.org, Oct 08, 2008

@jasondaly: It looks like you want the "Files" controller. Instead of selecting a key based on PATH_INFO (what Groups does), you just give it the piece of the array you want:

if (isset($include_script_groups[$param1])) {
    Minify::serve('Files', array('maxAge' => 31536000,
                                 'files' => $include_script_groups[$param1]));
} else {
    // 404
}
Comment by amitkhosla.jobs, Oct 22, 2008

how to call this peice of code Which url i should give?

"if (isset($include_script_groups$param1?)) {

Minify::serve('Files', array('maxAge' => 31536000,
'files' => $include_script_groups$param1?));
} else {
// 404
}"

When i try http://localhost/php/min.php?param1=scripts/script.js it says HTTP/1.0 400 Bad Request

though its working fine for the groups if i make grouping in php only. But what i want is i want to minify all the files in the parameter i pass.

Comment by st...@mrclay.org, Oct 23, 2008

if (isset($include_script_groups[$_GET['param1']])) { ...

Comment by covifox, Jan 13, 2009

Hi all. Ummm... a small suggestion:

I have Minify located in a static server and I used rewrite rules to serve false phisical files, stored through automatically merging arrays. This can output several 404 errors, especially serving groups, and I decided use the Quiet mode to check this.

I think can be useful (in quiet mode) a few more data, in the options array wich are returned from Base Controller when happen a error, think you?

I.Ex. and above all: a simple list of files that aren't found, or causes errors, instead the content item or another extra item.

  'success' => boolean false
  'statusCode' => int 400
  'content' => string ( true === debug ) ? list_of_wrong_files : Public error message (length=0)
  'headers' => 
    array
      empty

Cheers and congrats, I like your work.

Comment by prem.pillai, Mar 13, 2009

Can anyone here help Zend framework users to set this up. Thanks in advance.

Comment by st...@mrclay.org, May 12, 2009

@covifox: In config.php set $min_errorLogger = true; and check the HTTP headers in 400 responses (or check FirePHP) for errors.


Sign in to add a comment
Hosted by Google Code