Drupal 5: Minify and aggregate all javascript files to increase page load time performance

Adding this code to your Drupal site can improve two sections of a YSlow report, "Make fewer HTTP requests" and "Minify JS". This function minifies and aggregates your javascript into a single file. It requires the Google code library jsmin-php (http://code.google.com/p/jsmin-php/).

Stick this function in your template.php file in your theme directory:

<?php
function minify_scripts($scripts) {

  // define paths
  $jsMinFileName = 'jsmin_minified.js';
  $jsMinAbsolutePathDir = getcwd() . '/' . file_directory_path();
  $jsMinAbsolutePath = $jsMinAbsolutePathDir . '/' . $jsMinFileName;
  $jsMinRelativePath = base_path() . file_create_path($jsMinFileName);

  // check to see if file is writable
  if (
    (!file_exists($jsMinAbsolutePath) && !is_writable($jsMinAbsolutePathDir))
    ||
    (file_exists($jsMinAbsolutePath) && !is_writable($jsMinAbsolutePath))
    ) {
    return $scripts;
  }

  // include js minify library
  require_once('jsmin-1.1.1.php');

  // split $scripts on new line
  $exploded = explode("\n", trim($scripts));

  $minifiedJS = "";
  foreach ($exploded as $k => $v) {

    // ensure this line is javascript
    if (!(substr($v,0,7)=='<script' && substr($v,-9)=='</script>')) continue;

    // convert <script> to xml
    $xml = simplexml_load_string($v);

    if ($xml['type']=='text/javascript' && strlen($xml['src'])) {

      // define path to old file
      $oldFile = getcwd() . $xml['src'];

      // minify javascript
      $minifiedJS .= JSMin::minify(file_get_contents($oldFile));

      // unset exploded array entry
      unset($exploded[$k]);

    }

  }

  // check to see if javascript has not been minified
  if (strlen($minifiedJS)==0) return $scripts;

  // write file
  file_put_contents($jsMinAbsolutePath, $minifiedJS);

  // re-index array
  sort($exploded);

  // add entry
  $exploded[] = "<script type='text/javascript' src='$jsMinRelativePath'></script>";

  return implode("\n", $exploded);

}
?>

In your page.tpl.php theme file, replace this line:

<?php print $scripts ?>

with:

<?php print minify_scripts($scripts); ?>

You can also improve your score in the "Put JS at the bottom" section by ensuring this line of code resides at the bottom of your page.tpl.php file. I insert it just before this line:

<?php print $closure; ?>