Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Trim the Fat

JavaScript can benefit from many of the same optimization techniques used with HTML and CSS. Whitespace removal, crunching and obfuscation, file consolidation, and compression can all be used singly or in combination to shrink your scripts. Scripts can typically be reduced by 50 to 70 percent, while combining techniques on amenable files can yield savings of 80 to 90 percent, or a factor of 5 to 10 times smaller.

JavaScript offers more opportunities for optimization than (X)HTML and CSS because you can name your own variables, functions, and objects. The only names you can't abbreviate are the built-in statements and methods like document.getElementById().

As you've no doubt discovered, JavaScripts can become quite large, which can slow down the display of web pages. Any external scripts referenced in the head of your document must load before any body content displays. Even with smaller .css and .js files, it is important to minimize the number of HTTP requests as each one adds an indeterminate delay. The easiest way to optimize JavaScript is to trim the fat in the first place. Strive to add only features that will benefit users and save them time.

What About Legibility?

The knock against optimized scripts is that they are hard to read. This can be a good thing, because some authors want to obfuscate their code to make it difficult to copy and reverse engineer. However, optimized code is difficult to maintain and update. I recommend adopting a parallel strategy like the one you used for optimized HTML files. After you debug your code (which is fully commented and self-describing, right?), optimize it by hand or automatically optimize it to another file, like this:

script.js
script_c.js

Link to script_c.js for the added speed, and perform any edits on the original script.js, which you can then reoptimize.

Remove Whitespace

Well-written JavaScripts tend to have a lot of whitespace for better legibility. Indents, spaces, and returns make your code easier for you and others to read and modify; however, your browser doesn't care how pretty your code is. With a couple of exceptions, the JavaScript parser scans your script looking for tokens and ignores excess whitespace. So instead of this:

function printArray(a) {
  if (a.length == 0)
    document.write(" Array is empty");
  else {
    for (var i = 0; i < a.length; i++) {
      document.write(a[i] + " <br>");
    }
  }
}

Do this:

function printArray(a){
if(a.length==0)
document.write("Array is empty");
else{
for(var i=0;i<a.length;i++){
document.write(a[i]+"<br>");
}
}
}

Automatic Semicolon Insertion

The ECMAScript specification requires browsers to automatically insert semicolons where they are needed.2 Although they are optional, ending your lines with semicolons is good defensive programming practice. Semicolons are also required by most optimization strategies that remove excess whitespace. Without semicolons, removing whitespace can cause unintended consequences, such as running lines together. They also help programmers avoid errors. (Let's save programmers some time, too.)

Cut the Comments

Commenting your code is good programming practice, but comments take up valuable space. What's a programmer to do? There are two approaches to cutting comments: abbreviate your comments or remove them entirely. So instead of this (from PopularMechanics.com):

function gotoFinList() {

// "SAVE & FINISH" 
// this changes the bottom frameset to include a button to return to the homepage 
// it also submits the form in the main frame that will then generate a list of pages
// added during content editing.

Do this:

function gotoFinList() {

// chgs bottom frameset 2 incl button 2 ret 2 home 
// also submits form in main form and gen list of pgs
// added during content editg

Or even better:

function gotoFinList() {

You can use the parallel approach mentioned previously to keep a fully commented version for future updates.

  • + Share This
  • 🔖 Save To Your Account