I’m happy people are finding the article on javascript optimization useful. But I made a giant, horrible mistake. A mistake that befalls many tutorials.

I didn’t include actual, working examples for you to play with. You can talk all you want, but until you’ve got some code, it’s just theory and listless sighs. And without seeing the code walk (or run! Get it?), it’s hard to believe that it really works. So here’s some live, working examples to show these techniques in action:

The examples are free and in the public domain. However, if you find it useful I’d appreciate you sharing it with friends or dropping me a note. I like knowing what explanation styles work so I can do more of it in the future.

And now, the guided tour of what you’ll see in the zip file.

## Eliminate Tedium: Use Scripts

Automate, automate, automate! I’ve created a set of batch files (and .sh files for you Linux/UNIX gurus) to get you started:

• makeall.bat: Runs the commands below
• make_libraries.bat: Combines *.js into “allfiles.lib.js”, and combines files prefixed with “example” into “example.lib.js”.
• pack_js.bat: Compresses *.js and creates *.js.packed
• add_cache_header.bat: Inserts the PHP caching header into the .js.packed files, creating js.packed.php
• cleanup.bat: Removes generated files, leaving you with your original .js files.

These are templates – modify them to suit your own needs. If you find yourself typing a command again and again, throw it into a script.

## Compressing Javascript

I’ve included custom_rhino.jar which does the compression (more info).

There are a few javascript files for demo purposes. The first is example_compressed.js, which has extremely long variable names in various scopes (local and global). Take a look at this sucker, it’s ripe to get crunched by Rhino:

/* these names are global, so will not get compressed (could be used elsewhere) */
var LongName = 1;
var OtherLongName = 2;
var ReallyReallyLongName = 3;
var AbsurdlyLongNameImNotQuiteSureWhyAnyoneWouldUseThisButItIsGoodForExamples = 3;

/* these names are local to foo(), and will get compressed. Isn't Rhino awesome? */
function foo(){

var LongName = 1;
var OtherLongName = 2;
var ReallyReallyLongName = 3;
var AbsurdlyLongNameImNotQuiteSureWhyAnyoneWouldUseThisButItIsGoodForExamples = 3;
var LongName = 1;
var OtherLongName = 2;
var ReallyReallyLongName = 3;
var AbsurdlyLongNameImNotQuiteSureWhyAnyoneWouldUseThisButItIsGoodForExamples = 3;
(repeated...)
return 0; // of course <img src="http://betterexplained.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" />
}



A typical “javascript compressor” will simply remove extra spaces and comments, which doesn’t help much. Rhino actually analyzes your code: when it sees global variables, it knows the name shouldn’t be changed since other scripts may reference them.

But local variables are another story. Since locals are only referenced inside of their function, they are ripe for squashing. This is your javascript on Rhino:

var LongName=1;
var OtherLongName=2;
var ReallyReallyLongName=3;
var AbsurdlyLongNameImNotQuiteSureWhyAnyoneWouldUseThisButItIsGoodForExamples = 3;

function foo(){
var _1=1;
var _2=2;
var _3=3;
var _4=3;
var _1=1;
var _2=2;
var _3=3;
var _4=3;
var _1=1;
var _2=2;
...
return 0;
}


Any questions?

Rhino trampled the variable names and replaced them with the shortest identifiers it could find: _1, _2, etc. This saves a lot of space, and has the side-effect of partially obfuscating your code (if you are looking for that sort of thing).

Now here’s the fun stuff: example_imported.js and example_delayed.js don’t do anything special, except call a logging function that shows when they were loaded.

Check out sample.html

<html>
<!-- only put scripts here if you really need to -->
<body>

<!-- Scripts that need to run first -->
<script src="import.js"></script>
<script>
/* Simple logger -- looks for div with id "log".
We want this available from the get-go. */

function log(str){
var logger = document.getElementById("log");
if (logger){
logger.innerHTML += new Date().toString() + ": ";
logger.innerHTML += str;
logger.innerHTML += "<br/>";
}
}
</script>

<!-- content, images, tables, etc. -->
Put content here...

<div id="log">
</div>

<!-- include packed version -->
<script src="example_compressed.js.packed"></script>

<!-- dynamic import -->
<script>
$import('example_imported.js'); </script> <!-- delayed loading --> <script> function loadDelayedScripts(){$import('example_delayed.js');
}

var delay = 5; // wait and then load the file
</script>

<!-- other heavy scripts, tracking code, etc. -->
</body>
</html>


Take a look at the result:

Happy hacking.

## Questions & Contributions

1. sachin says:

I want simple material on array pointer graphics etc in C++ Java

2. Kalid says:

Hi Sachin, thanks for the suggestion.

3. This is a very useful article! Very nice work! Keep up!

4. Great thanks for the useful suggestions. will try to implement them in my website.

5. very very useful. kudos man. never read a better article on JS optimisation. congrats

6. This tutorial seems to be exactly what I need. I am downloading the files right now, thanks!

7. Kalid says:

9. kalid says:

Thanks Jules. Good idea.

10. Sappy says:

Thank you so much . it’s vry helpful for speed up website

11. I compress css using htacces my website, but now the writing look less attractive (unlike the original).

how to reduce the burden by java script but does not affect the look of the website in general?

12. thank you bag this tutorial, but sometimes I like to confuse yourself

because very often wrong in placing an html code or script, so although there are signs that one behind me write, direct definitely confused myself