It is advised, when deploying a live website, to group all your Javascript files into a single one, and reduce its size
by removal of all unnecessary clutter. You obviously get a few nasty
surprises the first time you do this, such as dead code (or debug-only
code) being included or two incompatible files being included together.
The usual answer to this, like with any integration-related issue, is
to perform continuous integration, and generally make sure during development that the final product works as it should.
Tip #1 - Keep it all together
I generally keep all of my javascript together in one single file, which is accessed through http://domain/all.js
or something like that. Of course, that file is in fact generated from
a well-tended garden of neatly arranged source files, but the intent is
that every single visit on the development website will bring along all
the code that could possibly conflict with it, to identify issues as
soon as possible.
This means I have access to a Javascript preprocessor, because generating a single file already involves reading all the files.
Tip #2 - Conditional inclusion
Difficult bugs appear on platforms with no debuggers, which
means you need to be able to track the progress of your application
with logging. You don't want to have those log lines appearing on the
live website, though. In the same way, runtime assertions are useful
while developing, so you get a clean "Expected string, got array" error
message right after you call a function with incorrect parameters,
instead of a "object has no member charAt" ten stack layers deeper.
Yet, assertions use up room, and tend to die in a flashy and
unprofessional way on a live website.
An overly intrusive preprocessor can prevent your code from running
if not preprocessed. It also means whatever tool you use to edit
Javascript source cannot recognize the syntax anymore, which is bad.
The solution (which I learned from the PHP preprocessing techniques of
the folks at IntellAgence) is to embed preprocessing information in comments.
Need some logging?
/*<*/ log('Hello'); /*>*/
Need to check something at runtime?
/*[*/ Assert.areEqual(x,y); /*]*/
A simple regular expression can remove these from the final code,
but you can also selectively disable them by removing the second slash
of the first comment :
/*[* Assert.areEqual(x,y); /*]*/
Tip #3 - Named anonymous functions
Quick reminder: Javascript allows you to define anonymous functions using a lambda-like construct:
function(x) { return x + 1 }
This acts like a function literal (pretty much like a string literal
works for strings, or an array literal works for arrays). In fact, if
you're doing any kind of serious Javascript, you probably have
anonymous functions all over the place, such as callbacks to
asynchronous operations:
$('button').click(function(){ alert('Hello') });
Or you might be defining member functions for your classes:
className.prototype.setFoo = function(x){
this._foo = x;
};
When you get a runtime error, the debugger displays a stack trace
containing the names of the functions and the places where they were
called. So, if you were using many anonymous functions, you get
neck-deep into layers of "anonymous" on your stack trace. Sure, you can
click on every single one of them to understand what is happening, but it is way faster to get that knowledge from looking at meaningful names.
Javascript allows you to give names to anonymous functions. In fact,
this is how recursive functions can be defined as lambdas (a feature
that OCaml lacks, for instance). So you can write the following and see
it appear in a stack trace:
$('button').click(function _onButtonClick(){ alert('Hello') });
className.prototype.setFoo = function _className_setFoo(x){
this._foo = x;
};
I start all names with underscores, because a simple /function _[A-Za-z0-9_]*/ in my preprocessor can identify and remove all those names when I don't need them.
Tip #4 - Are your callbacks called?
The Javascript function model lets you write a function that
forwards whatever it was doing to another function. You can even log
some information along the way...
function trace(f) {
return function () {
log('%o.%s(%o)',this,name(f),arguments);
return f.apply(this,arguments);
}
}
The preprocessor instructions for conditional removal let you do this only in specific circumstances:
className.prototype.setFoo = /*[*/ trace /*]*/
(function _className_setFoo(x){
this._foo = x;
});
It can also be quite practical to use a variant of the trace
function that stores all functions it traces in an array, and removes
them from the array the first time they are called. This can be useful
when debugging calls to asynchronous functions that you write, because
you might forget to call the callback function when you are done, and these bugs are otherwise quite hard to identify.
Tip #5 - Do not rely on closures too much
Closures in Javascript means you can write this, and have the inner function use the variable from the outer function :
function outer(a) {
var b = a + 1;
return function inner(c) {
return b * c;
}
}
Closures are extremely useful. However, Javascript has a nasty habit
of creating variables at global scope whenever you try to write to a
variable that doesn't exist. For instance, the following function is
not re-entrant because an accidental typo makes it use a global
variable :
function person() {
var aeg = 18;
return {
setAge : function(a) { age = a },
canDrink : function() { return age > 20 }
}
}
A good solution, I believe, is to rely on object members instead of
variables. Inappropriately using an object member is harder than
inappropriately using a local variable, because the former does not
default to "look in the global scope". Besides, every function beyond a
certain level of inner state complexity deserves to be adapted to a
more structured object style with its data as private members (if only
because this is way easier to explore with a debugger).
|