Fixing The Drupal JavaScript Problem

JavaScript is a second class language within Drupal. This shouldn’t be a surprise and there is no one to point the blame at. Drupal has been around since JavaScript was used for window dressing (like snowflakes falling down your page). In the last several years JavaScript has blossomed and is used everywhere. Drupal has taken notice and recent versions of Drupal ship with a lot of JavaScript. Drupal 7 ships with jQuery, jQuery UI, and several other useful plugins.

But, the custom JavaScript within Drupal looks a lot like it was written by PHP developers who learned just enough JavaScript to be dangerous. I say that as someone who has contributed to producing sub-par JavaScript. As a community it is time we fix this problem. We need to grow some solid JavaScript developers and make the world of Drupal JavaScript a better place.

How Well Do You Know JavaScript?

How well do you know JavaScript? To test your knowledge lets take a look at two snippets of code from drupal.js (Drupal 7 Beta 2). The first snippet comes from `Drupal.checkPlain`:
for (var character in replace) {
  var regex = new RegExp(character, 'g');
  str = str.replace(regex, replace[character]);
}

The second snippet comes from Drupal.theme:

for (var i = 1, args = []; i < arguments.length; i++) {
  args.push(arguments[i]);
}

In each of these can you identify a point to provide significant performance improvement or a place where the code shows a lack of understanding for how JavaScript works? They are there if you know what to look for.

Moving Forward From Here

I point out this ugly underbelly because I love working with Drupal and want to see it improve. I hope we can start improving our JavaScript now so Drupal 7 contrib can be an improvement over Drupal 6 and Drupal 8 JavaScript will outshine Drupal 7.

The first step towards making JavaScript better in Drupal is knowing how to write good JavaScript. If you are interested in getting started down the road to writing better JavaScript I’d invite you to take a look at a few options. There are many more beyond these. The following items just came to my mind first.