Supercharging Javascript in PHP

I am an unapologetic stickler for speed when it comes to Web applications. A Website should be fast and responsive. The average attention span of a user is about eight seconds. One of the quickest and easiest ways to speed up your Website is by improving your Javascript delivery and usage. This is a HOWTO guide on getting the best Javascript performance you can.

If you haven't yet, install the Firefox plugins Firebug and YSlow. They're invaluable for profiling page loading performance

For these posts I'm going to use PHP running on Apache for my examples. It's a popular platform but of course not the only one. These principles apply equally well to any Web technology stack.

I'm also a big fan of URL rewriting. Enabling URL rewriting is as simple as uncommenting mod_rewrite from your Apache config file (typically httpd.conf). Many PHP stacks (eg XAMPP) have this enabled by default. Most if not all hosting providers will have this available on even their cheapest plans.

Over the years I've sometiems encountered issues with dynamically generated Javascript and CSS in certain browsers. As such--although not strictly necessary--I like to give dynamically generated Javascript and CSS the "correct" extensions of .js and .css with URL rewriting. So instead of:

<script src="/javascript.php"></script>

you're better off having a URL like "/javascript/site.js" mapping that to a PHP script. With Apache and mod_rewrite this can be as simple as putting the following lines into an .htaccess file in your document root.

RewriteEngine On
RewriteBase /
RewriteRule ^javascript/site\.js$ /javascript.php [L]

Or I prefer something like:

RewriteRule ^javascript/(\w+)\.js$ /javascript.php?site=$1 [L]

This allows you to create "bundles" of Javascript files. One part of your site might require YUI and another jQuery. I'm going to use this version below. >All of these posts will assume the above is being used.

My goal is to take well-established best practices and combine them into an easy-to-use PHP-oriented solution so you can easily do things the right way without loss in flexibility or power.

3 comments:

John Rockefeller said...

When you add the extra mod_rewrite step it makes it slower than just using the original php file without the rewrite, correct? I mean, it'll be negligible, but that was what your first paragraph in the post was all about.

Also, what's the harm in having the extension be .php? Other than it satisfies some internal urge to have it .js instead?

Anonymous said...

"I am an unapologetic stickler for speed when it comes to Web applications. A Website should be fast and responsive."

Wouldn't be time to make this site faster then. Oooops, just kidding :)

Thanks for the information you share on this blog, even if it's really terribly slow!

Edward Hotchkiss said...

To Anonymous ... he IS using Blogger, note the .ico!

Post a Comment