PHP script to join multiple javascript files into one file, compress with gzip, set expiration headers

Started on the old forum in July 2015 · view the original in the archive · old links redirect here

No replies · 86 views · started 11 years ago · 1 min read

GumSlone Administrator Principal · 1,690 posts #1

Speed Up your sites with the script below.

Join multiple javascript files into one file, compress them with gzip and set expiration header.

replace:

include('./js/file1.js');
include('./js/file2.js');
include('./js/file3.js');

with your js files

<?php
$offset = 60 * 60 * 24 * 30; // Cache for a day
header("Content-type: text/javascript");
header ("Cache-Control: max-age=" . $offset . ", must-revalidate");
header ("Expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT");
function compress($buffer) {
/* remove comments and empty lines */
//$buffer = preg_replace('!/\*.*?\*/!s', '', $buffer);
$buffer = preg_replace('(// .+)', '', $buffer);
$buffer = str_replace(array("//\r\n", "//\n"), '', $buffer);
$buffer = preg_replace('/\n\s*\n/', "\n", $buffer);
return $buffer;
}
ob_start();
include('./js/file1.js');
include('./js/file2.js');
include('./js/file3.js');
$out = ob_get_contents();
ob_end_clean();
$out = compress($out);
if(strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip"))
{
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
ob_start('ob_gzhandler');
}
echo $out;
?>

Advertise your mobile site for FREE with AdTwirl

External image (may be gone)

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close