0% found this document useful (0 votes)
27 views

Op Zax 09 A

This document discusses techniques for making JavaScript code more reusable and efficient, including JSMin and Packer for code compression. JSMin removes all whitespace and comments to minimize file size, while Packer uses a more advanced approach to dramatically reduce code size by over 50% in some cases. The document also discusses distributing code through services like the JavaScript Archive Network to allow others to reuse code modules in a standardized format.

Uploaded by

cejijit238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Op Zax 09 A

This document discusses techniques for making JavaScript code more reusable and efficient, including JSMin and Packer for code compression. JSMin removes all whitespace and comments to minimize file size, while Packer uses a more advanced approach to dramatically reduce code size by over 50% in some cases. The document also discusses distributing code through services like the JavaScript Archive Network to allow others to reuse code modules in a standardized format.

Uploaded by

cejijit238
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

7273ch03final.

qxd 11/16/06 8:21 AM Page 55

CHAPTER 3 ■ CREATING REUSABLE CODE 55

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.

Listing 3-15. Code for Determining a User’s Browser

// (c) 2001 Douglas Crockford


// 2001 June 3
// The -is- object is used to identify the browser. Every browser edition
// identifies itself, but there is no standard way of doing it, and some of
// the identification is deceptive. This is because the authors of web
// browsers are liars. For example, Microsoft's IE browsers claim to be
// Mozilla 4. Netscape 6 claims to be version 5.

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;
}

Listing 3-16. A Compressed Copy of the Code in Listing 3-15

// 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

56 CHAPTER 3 ■ CREATING REUSABLE CODE

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.

Listing 3-17. Portion of Code Compressed Using 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

CHAPTER 3 ■ CREATING REUSABLE CODE 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.

Listing 3-18. A Sample JSAN Module (DOM.Insert)

// 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' )

// If JSAN isn't loaded, it will throw an exception


} catch (e) {
throw "DOM.Insert requires JSAN to be loaded";
}

// Make sure that the DOM namespace exists


if ( typeof DOM == 'undefined' )
DOM = {};

// Create a new DOM.Insert constructor, which inherits from 'Object'


DOM.Insert = Class.create( 'DOM.Insert', Object, {
// The constructor which takes two arguments
initialize: function(element, content) {
// An element to insert HTML into
this.element = $(element);

// The HTML string to insert


this.content = content;

// Try inserting the HTML using the Internet Explorer way


if (this.adjacency && this.element.insertAdjacentHTML) {
this.element.insertAdjacentHTML(this.adjacency, this.content);
7273ch03final.qxd 11/16/06 8:21 AM Page 58

58 CHAPTER 3 ■ CREATING REUSABLE CODE

// Otherwise, try it the W3C way


} else {
this.range = this.element.ownerDocument.createRange();
if (this.initializeRange) this.initializeRange();
this.fragment = this.range.createContextualFragment(this.content);
this.insertContent();
}
}
});

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
■■■

Tools for Debugging


and Testing

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

You might also like