Posts Tagged → javavascript
Small PHP Script to Load All Javascript in One Request
It is generally a good idea to try to reduce the number of HTTP requests for a web page to load more quickly. If you have many javascript files, it is ideal to put them into a single file and load that one file. Unfortunately, this can be difficult to manage especially when using scripts that have upgrades periodically (such as Prototype and Scriptaculous, jQuery, etc.). A simple solution is to have a fast script that puts all of the javascript into a single file on the server side. Here is that script:
<?php
$time_start = microtime_float();
$files = $_GET['load'];
// Make sure the input is not unreasonably large or contains any characters that would allow access of files outside of this directory or hosted elsewhere (i.e. no colons or slashes)
if (strlen($files)>200 || preg_match('/[^a-zA-Z0-9.,_-]/',$files))
exit("Error with input");
$files_array = explode(',',$files);
$output = '';
foreach($files_array as $file) {
$file = $file.'.js';
if (!file_exists($file))
exit("File not found: $file");
$output .= "// ---------------- $file ----------------".PHP_EOL;
$output .= file_get_contents($file);
$output .= PHP_EOL;
}
$time_end = microtime_float();
$time = $time_end - $time_start;
$output .= "// Rendered by js_load in $time seconds";
header("Content-Type: text/javascript");
header("Content-Length: ".strlen($output));
echo $output;
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
This file should be called js_load.php and it should be placed in the same directory as all other js files. Usage would be:
<script type="text/javascript" src="/global/js/js_load.php?load=prototype,scriptaculous,effects,dragdrop,my_script"></script>
This runs nice and fast and does the trick. An improvement would be to store a cached version of the output and to check the file dates when accessed and only update the cache when there is an update, rather than have to read through and output the actual files each time.
Note, some testing showed almost no difference in speed between file_get_contents() and fpassthru().