Skip to content

Instantly share code, notes, and snippets.

@Gisleburt
Last active December 11, 2015 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gisleburt/4540358 to your computer and use it in GitHub Desktop.
Save Gisleburt/4540358 to your computer and use it in GitHub Desktop.
Bundles all your JS files into one file.Point your html script src at this file, and put all your files in the $files array. Turn devMode on if you're updating your js files a lot and it will regenerate if any are newer than the current bundle.
<?php
//
// Edit these bits
//
$bundleFileName = __DIR__.'/_bundle.js';
$devMode = true;
$files = array(
);
if(!$files)
$files = getLocalFiles();
$files = makeRelative($files); // Comment out if you don't want $files to be relative to the script
//
// Create and/or throw out the file
//
if(!is_readable($bundleFileName) || ($devMode && isOld($bundleFileName, $files)))
createBundle($bundleFileName, $files);
outputJS($bundleFileName);
//
// Functions
//
function outputJS($file) {
if(strstr($_SERVER['HTTP_USER_AGENT'],'MSIE')==false) {
header('Content-type: text/javascript');
header('Content-Disposition: inline; filename=\'download.js\'');
header('Content-Length: '.filesize($file));
} else {
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename=\'download.js\'');
header('Content-Length: '.filesize($file));
}
header('Expires: Fri, 01 Jan 2010 05:00:00 GMT');
if(strstr($_SERVER['HTTP_USER_AGENT'],'MSIE')==false) {
header('Cache-Control: no-cache');
header('Pragma: no-cache');
}
include($file);
}
function isOld($bundleFile, array $files) {
foreach($files as $file)
if(filemtime($file) > filemtime($bundleFile))
return true;
return false;
}
function makeRelative($files) {
foreach($files as $i => $file)
$files[$i] = __DIR__."/$file";
return $files;
}
function getLocalFiles() {
$allFiles = scandir(__DIR__);
$files = array();
foreach($allFiles as $file)
if($file[0] !== '_' && substr($file,-3)==='.js')
$files[] = $file;
return $files;
}
function createBundle($filename, array $files) {
$nl = "\n\r";
$date = date('Y-m-d H:i:s');
$output = "// Created: $date $nl";
foreach($files as $file)
$output .= file_get_contents($file).$nl;
file_put_contents($filename, $output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment