Fixing HTML(5)

Douglas Crockford has posted an sublimely simple article on fixing HTML by making HTML 5 simple and sublime. Since he’s the JavaScript God, his suggestions bode well for anyone working in the DHTML realm. Let’s hope someone at the W3C listens to him.

Avoiding .innerHTML slowdowns

You might already have figured out that .innerHTML can be way faster than using the DOM. But did you know that when clearing out existing code the DOM can be faster than .innerHTML? Take a look the article When innerHTML isn’t fast enough to see some impressive benchmarks and a simple solution.

YSlow - Find out why your page is slow

YSlow is a Firefox plug-in which analyzes web pages and tells you why they’re slow based on Yahoo’s rules for high performance web sites. These rules are:

  1. Make Fewer HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires Header
  4. Gzip Components
  5. Put CSS at the Top
  6. Move Scripts to the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags

Definitely worth checking out if you need to tweak every ounce of performance you can get on certain pages.

JavaScript on Rails

With the rise in popularity of the Ruby on Rails framework it was only a matter of time before someone tried to implement it using JavaScript. Of course, when that someone happens to work at Google then all hell breaks loose. Here’s Steve Yegge’s reply to all the hype, which also hints at the evolution of Rhino, which is essentially JavaScript for Java. If you’re not familiar with Rhino, check out what Steve has to say about it:

Rhino…was written with an eye for performance. The Rhino code base reads almost like C code: it avoids allocation and does as much as possible with jump tables to avoid the overhead of virtual method lookups. It has two code paths: a bytecode interpreter that runs in a tight loop, and an optimizing Java bytecode compiler that turns many expensive-ish JavaScript property lookups into Java local or instance-variable lookups. It’s a pretty serious piece of software.

When you start digging into Rhino, you find unexpected depth. JavaScript (unlike Perl, Python and Ruby, at least today) actually has a real specification, and Rhino follows it rigorously, aiming for complete SpiderMonkey compatibility within the bounds allowed by the different language platforms. Rhino also offers rich configurability, has well-defined multi-threading semantics, has a full set of hooks for debugging and profiling, and much more besides. There’s a lot under the hood.

Oh, and Sun is now bundling it with the JDK; it’s javax.script in Java 6. With that kind of endorsement it would have been hard to justify using anything else, even if some language other than Jython or JavaScript had been up for consideration.

With an endorsement like that and the potential for easy integration in an IDE with Google’s GWT you can expect to hear a lot more about Rhino on Rails in the coming year.

Default arguments in JavaScript

I sometimes run into people who need (whatever the reason may be) to be able to give default argument values in a JavaScript function. Similar to what you find in C++:

void foo(int a, int b = 42) {
//b is set to 42 automatically if no value is defined
...
}

I felt an urge to do it, so I sat down for a few minutes, trying to conjure something nifty that would be intuitive enough for even me to use.

The solution I came up with, and that hopefully will put an end to the default-arguments rant for good.

The solution is quite simple, and very intuitive. It may have some shortcomings but keep in mind I didn’t explicitly write it for you. You could probably modify my solution to fit your needs anyway.

I’ve seen a lot of developers (including myself, long time ago) using this pattern as a workaround for the lack of built-in support for default-arguments.

function foo(a, b)
{
a = typeof(a) != 'undefined' ? a : 42;
b = typeof(b) != 'undefined' ? b : 'default_b';
...
}

Which most developers probably find sufficient, I don’t.

The solution may look scary at a quick first glance, but bear with me. I’ll start by writing the framework-code. The code that will be required for this thing to work.

Function.prototype.defaults = function()
{
var _f = this;
var _a = Array(_f.length-arguments.length).concat(
Array.prototype.slice.apply(arguments));
return function()
{
return _f.apply(_f, Array.prototype.slice.apply(arguments).concat(
_a.slice(arguments.length, _a.length)));
}
}

See that wasn’t so scary :) .

In order for this to work you have to declare you functions in a special way. There are basically two ways of declaring a function.

function foo(a, b)
{
...
}

Is identical to (apart from the lexical difference, and some other minor things)

var foo = function(a, b)
{
...
}

In order for this solution to work you have to declare all functions on which you wish to have default-arguments the latter way.

Usage

var foo = function(a, b)
{
...
}.defaults(42, 'default_b');

Is identical to the first code-block but without adding any code in the function-body.

Example

var bar = function(a, b)
{
}.defaults('default_b');
bar();
// a = undefined, b = 'default_b'
bar(1);
// a = 1, b = 'default_b'
bar(1, 'some_value');
// a = 1, b = 'some_value'

Finally, a decent JS Tutorial!

Essential Javascript - A Javascript TutorialThe lack of a proper JavaScript tutorial on the web is well known to the members of this channel. We’ve even tried our own half-arsed versions once or twice. But I was pleasantly surprised to find Essential Javascript - A Javascript Tutorial.

This tutorial is clean and concise, covering basics such as variables, functions, events, math and dates. A nice feature is the code doesn’t look like it dates to 1998. The tutorial is actually several tutorials, and also covers popular topics such as AJAX for Noobs and JSON. An excellent resource for those just learning the language or eager to dive into more advanced topics but lacking fundamentals.

Great scripts for sprucing up your web applications

Igglo.co.uk has posted a collection of links for 15 interesting javascript scripts.

While none of the scripts are new they are all both nice and potentially useful for sprucing up your site or webapp. Some of the scripts aim at visual effects such as loading and fading an image or putting hot spots on a map, while others such as Lightbox are regularly mentioned on the irc channel. There are also updated versions of ubiquitous tools like a date picker calendar and auto complete.

These are not just snippets of code but full blown scripts, so you should get productive results from them right away, and all are free for anyone to use.

Prototyping with the JavaScript Prototype Object

One of the most important features in JavaScript is the ability allow objects to inherit methods through the use of prototyping. Anyone who had a toolkit of JavaScript functions is well served by also putting to use prototypes to fill in the gaps where existing functions are missing, such as a simple String.trim() function.

A lot of prototyping toolkits exist, with Prototype (yeah, they stole the name) being the most popular one, but at 92KB, some consider Prototype a bit heavy for what they need. If you happen to be one of those people, then you may be interested in picking and choosing prototype methods from the following two resources.

The first is Svend Tofte’s Usefull Prototype Methods for JavaScript (sic). Svend’s collection of a dozen methods weighs in at a tiny 2KB, and it’s all modular enough that you can pick and choose the methods you like the most.

The second is Henlock’s Ten JavaScript Tools Everyone Should Have. I find his methods to be a bit more useful than Svend’s, and he mentions a few additional resources at the bottom of his page.

So what prototype methods are a must for you?

JavaScript Cheat Sheet

I found an excellent JavaScript Cheat Sheet recently when someone was asking for JS documentation. It covers everything from functions and methods to XMLHttpRequest and regular expressions. Best of all, it has both PNG and PDF versions available for download.

Everyone should have some sort of quick reference when it comes to JavaScript, the language’s ease of use lends itself to a light document that can quickly be looked up. Personally I’ve only ever used O’Reilly JavaScript Pocket Reference as my JS book. For anything more complicated I was always better served by Google.

RTFAPI!

If you don’t know how to us Google effectively and have yet to memorise all the APIs out there then you might enjoy the consolidated practicality of gotAPI.com. Although the interface may leave something to be desired, gotAPI.com’s usefulness cannot be denied.