Supercharging Javascript, Part 1: Make as Few HTTP Requests as Possible

The more Javascript files you have, the slower your page will load. I've seen some big sites that have over 20 external Javascript files, which is bewildering. Ideally you should have exactly one. That doesn't mean you can't develop with multiple Javascript files. Throw in jQuery and a few plugins and you might be up to ten or more before you even put in your own. That's not a problem because we're only concerned with what gets sent to the client.

So the first optimization we can make is to use our dynamically generated Javascript to combine all our Javascript files into a single HTTP payload.

<?php
// These no longer even need to be under the document root
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');

$bundles = array(
  'site' => array(
    'jQuery-1.3.2.js',
    'jquery.bgiframe.js',
    'jquery.dimensions.js',
    'supersubs.js',
    'superfish.js',
    'site.js',
  ),
);

$site = $_GET['site'];
if (!isset($bundles[$site])) {
  error_log("javascript.php: Unknown bundle '$site' requested");
  exit;
}
header('Content-Type: text/javascript');
foreach ($bundles[$site] as $file) {
  if (@readfile(SCRIPT_DIR . $file) === false) {
    error_log("javascript.php: Error reading file '$file'");
  }
}
?>

This rudimentary version can make a big difference if you have a lot of files (which you probably do if you're using jQuery or YUI). The above is based on a trivial example that uses the superfish jQuery plugin with (required and optional) dependencies and results in approximately 140k of Javascript. But we can do much better.

Next: GZip Everything

0 comments:

Post a Comment