Op Zax 09 A
Op Zax 09 A
JSMin
The premise behind JSMin is simple. It goes through a block of JavaScript code and removes
all nonessential characters, leaving only the purely functional code. JSMin does this by simply
removing all extraneous white-space characters (this includes tabs and end lines) and all com-
ments. An online version of the compressor can be found here: http://www.crockford.com/
javascript/jsmin.html.
To get a feel for what happens to the code once it’s been passed through JSMin, we’re
going to take a sample block of code (shown in Listing 3-15), pass it through the minifier, and
see its resulting output in Listing 3-16.
var is = {
ie: navigator.appName == 'Microsoft Internet Explorer',
java: navigator.javaEnabled(),
ns: navigator.appName == 'Netscape',
ua: navigator.userAgent.toLowerCase(),
version: parseFloat(navigator.appVersion.substr(21)) ||
parseFloat(navigator.appVersion),
win: navigator.platform == 'Win32'
}
is.mac = is.ua.indexOf('mac') >= 0;
if (is.ua.indexOf('opera') >= 0) {
is.ie = is.ns = false;
is.opera = true;
}
if (is.ua.indexOf('gecko') >= 0) {
is.ie = is.ns = false;
is.gecko = true;
}
// Compressed code
var is={ie:navigator.appName=='Microsoft Internet Explorer',java:
navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:
navigator.userAgent.toLowerCase(),version:parseFloat(
navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:
7273ch03final.qxd 11/16/06 8:21 AM Page 56
navigator.platform=='Win32'} is.mac=is.ua.indexOf('mac')>=0;if(
is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}
Notice that all of the white space and comments have been removed, dramatically cutting
down on the overall size of the code.
JSMin is perhaps the simplest JavaScript compression utility. It’s a great way to get started
using compression within your production code. When you’re ready to save additional band-
width, however, you’ll want to graduate to using Packer, which is a formidable and extremely
powerful JavaScript compression library.
Packer
Packer is by far the most powerful JavaScript compressor available. Developed by Dean
Edwards, it serves as a way to completely reduce the size of your code and expand and exe-
cute it again on the fly. By using this technique, Packer creates the optimally smallest code
possible. You can think of it as a self-extracting ZIP file for JavaScript code. An online version
of the script is available at http://dean.edwards.name/packer/.
The Packer script is quite large and very complicated, so it’s recommended that you not
try to implement this on your own. Additionally, the code that it generates has a couple hun-
dred bytes of overhead (in order to be able to extract itself), so it’s not perfect for extremely
small code (JSMin would be better for that). However, for large files, it is absolutely perfect.
Listing 3-17 shows an extract of the self-extracting code that is generated by Packer.
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,
String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[(function(e){return
d[e]})];e=(function(){return'\\w+'});c=1};while(c--){if(k[c]){p=p.replace(new
RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('u 1={5:2.f==\'t s
r\',h:2.j(),4:2.f==\'k\',3:2.l.m(),n:7(2.d.o(p))||7(2.d),q:2.g==\'i\'}1.
b=1.3.6(\'b\')>=0;a(1.3.6(\'c\')>=0){1.5=1.4=9;1.c=e}a(1.3.6(\'8\')>=0){1.5=
1.4=9;1.8=e}',31,31,'|is|navigator|ua|ns|ie….
The usefulness of compressing your code, and especially of using Packer to do so, cannot
be understated. Depending on how your code is written, you’ll frequently be able to reduce its
size by more than 50%, which can result in improved page load times for your users, which
should be a top goal for any JavaScript application.
Distribution
The final step of the JavaScript writing process is an optional one and depends mostly
upon your particular situation. If you’re simply writing code for yourself or a company,
you’ll most likely be simply distributing your code to other developers or uploading it to
your web site for use.
However, if you develop an interesting piece of code and wish to let the world use it
however they wish, this is where a service such as the JavaScript Archive Network (JSAN)
7273ch03final.qxd 11/16/06 8:21 AM Page 57
comes into play. JSAN was started by a couple of Perl developers who enjoyed the function-
ality and usefulness of CPAN (Comprehensive Perl Archive Network). More information
about JSAN can be found on its site: http://openjsan.org/.
JSAN asks that all modules submitted be written in a nicely formatted object-oriented
style, conforming to its particular module architecture. JSAN, in addition to its central
repository of code, has a means through which you can import external JSAN module depen-
dencies, which are required by your code. This can make it extremely simple to write inter-
dependent applications without worrying about which modules the user already has installed.
To understand how a typical JSAN module works, let’s look at a simple one, DOM.Insert,
which is available here: http://openjsan.org/doc/r/rk/rkinyon/DOM/Insert/0.02/lib/
DOM/Insert.html.
This particular module takes an HTML string and inserts it into a web page at a particular
point. In addition to it being nicely object-oriented, this module also requires and loads two
other JSAN modules, both of which are shown in Listing 3-18.
// We're going to try and include some other modules using JSAN
try {
// Load in the two required JSAN libraries
JSAN.use( 'Class' )
JSAN.use( 'DOM.Utils' )
The power of having cleanly written object-oriented, easily intractable JavaScript code
should be the hallmark of development for you, or any other web developer. It is through
this means that we are going to build upon and explore the rest of the JavaScript language.
As JavaScript continues to come into its own, the importance of this style of writing will only
increase and become more useful and prevalent.
Summary
In this chapter you saw different ways of building reusable code structures. Using the object-
oriented techniques that you learned in the previous chapter, you were able to apply them
and create clean data structures that are perfectly suited to multideveloper environments.
Additionally, you saw the best ways to create maintainable code, reduce JavaScript file size,
and package code for distribution. Knowing how to write nicely formatted, maintainable
code will save you countless hours of frustration.
7273ch04final.qxd 11/16/06 8:20 AM Page 59
CHAPTER 4
■■■
P erhaps the most time-consuming process when developing in any programming language
is that of testing and debugging your code. With professional-grade code it becomes of the
utmost importance to make sure that what you create is fully tested, verifiable, and bug-free.
One aspect that makes JavaScript so different from other programming languages is that it
isn’t owned or backed by any one company or organization (unlike C#, PHP, Perl, Python, or
Java). This difference can make it challenging to have a consistent base with which you can
test and debug your code.
To cut down on the amount of stress and work that you may have to endure, when
catching JavaScript bugs, any one of a number of powerful development tools can be used.
There exist tools (often in varying quality) for every modern browser. Using them makes
JavaScript development become a much more consistent picture, and one that seems
much more promising.
In this chapter I discuss the different tools that can be used to debug your JavaScript
code, then build solid, reusable testing suites with which to verify future developments.
Debugging
Testing and debugging are two processes that go hand in hand. While you should be building
comprehensive test cases for your code, you’ll most definitely hit strange errors that require
more attention. This is where the debugging process comes in. By knowing how to use the
best tools available, to find and fix bugs in your code, you can get your code back up and
working faster.
Error Console
The most accessible tool that’s available in all modern browsers is some form of an error
console. The quality of the console, the accessibility of the interface, and the quality of the
error messages all vary from browser to browser. Ultimately, you’ll probably find it best to
begin your debugging process with a single browser whose error console (or other debug-
ging extension) is best suited for developers.
59