Christian Heilmann

You are currently browsing the archives for the javascript category.

Archive for the ‘javascript’ Category

YUI on the go – load YUI components on demand

Friday, December 7th, 2007

This is one of my talks at the Yahoo! Frontend Engineering summit in London and it deals with the options of cutting down the size of the YUI library components. There have been many articles and posts about this subject already but none really explained the idea of using YAHOO_config to load components on demand instead of using the YUI loader.

This is also the trick I used to create the unobtrusive flickr badge v2.

Planning JavaScript for Larger Teams – Draft & Handout version

Wednesday, November 28th, 2007

I just found my original draft of my @mediaAjax presentation. I discarded it cause it was way too long for an hour talk and I didn’t know what do ditch:

Hope it is of use somehow.

JavaScript shortcut notations that shouldn’t be black magic to the “average developer”

Tuesday, November 27th, 2007

When publishing articles about JavaScript development you run into many rules set by publishers and editors. This is a great thing as it keeps us authors on our toes and makes us understand more about how much work successful publishing really is. However, it can also be terribly annoying, especially when older idioms just stick. One of them is that “the average developer” does not quite understand JavaScript shortcut notations.

Now, if you are “the average developer”, please give me 5 minutes of your time to get through the following, you’ll understand a lot more code out there and also spend a lot less time writing your own scripts.

Array shortcut notation – It is hip to be square

The first bugbear I have are arrays. These are terribly useful and omnipresent in JavaScript and still I find people who write convoluted things like:

var links = new Array();
links[0] = 'http://cuteoverload.com';
links[1] = 'http://icanhascheezburger.com';
links[2] = 'http://pencilsatdawn.wordpress.com';
links[3] = 'http://apelad.blogspot.com';
// ... ad nauseam ...

This is convoluted (you have to repeat the array name for every item) and also tricky to maintain. When you change the order (granted the order is of importance) you need to change the number, too. It is not necessary, as the numbering is done automatically for you. All you need to do is use the square brackets:

var links = [
  'http://cuteoverload.com',
  'http://icanhascheezburger.com',
  'http://pencilsatdawn.wordpress.com',
  'http://apelad.blogspot.com' // <-- last one, NO COMMA!
];

This makes it more obvious from a visual point of view, too. The indentation makes it easy to spy where the array begins and where it ends. Much less line noise to take in.

Notice that you need to separate each item with a comma, but make sure you don’t have a trailing comma at the last item. You can even nest arrays that way:

var links = [
  'http://cuteoverload.com',
  'http://icanhascheezburger.com',
  [100,200,20,'foo'],
  'http://pencilsatdawn.wordpress.com',
  'http://apelad.blogspot.com' // <-- last one, NO COMMA!
];

On that note, here’s another trick: to add a new item to arrays, you can either use the push() method or use the length property:

links.push('http://dailypuppy.com');
links[links.length] = 'http://bigeyedeer.wordpress.com';

Associative Arrays – OMG! Ponies!

One myth that keeps sticking is that JavaScript has a magical thing called associative arrays. These allow you to not just number the items but give them names instead! You find examples like:

var links = new Array();
links['Cute Overload'] = 'http://cuteoverload.com';
links['I can has cheeseburger'] = 'http://icanhascheezburger.com';
links['Pencils at dawn'] = 'http://pencilsatdawn.wordpress.com';
links['Hobotopia'] = 'http://apelad.blogspot.com';

This is treachery to the highest degree. It is a confusing JavaScript trait, as what you created here is not really an array, but an object. Want proof? – Do an alert(typeof links) or try alert(links[1]).

Object shortcut (literal) notation – getting curly.

So called associative arrays are actually objects, which means you will also find other scripts that took the earlier example serious and use the following instead:

var links = new Object();
links['Cute Overload'] = 'http://cuteoverload.com';
links['I can has cheeseburger'] = 'http://icanhascheezburger.com';
links['Pencils at dawn'] = 'http://pencilsatdawn.wordpress.com';
links['Hobotopia'] = 'http://apelad.blogspot.com';

Again we have far too much repetition. For objects, you have the Object Literal Notation as a shortcut, which basically is using curly braces:

var links = {
  'Cute Overload' : 'http://cuteoverload.com',
  'I can has cheeseburger' : 'http://icanhascheezburger.com',
  'Pencils at dawn' : 'http://pencilsatdawn.wordpress.com',
  'Hobotopia' : 'http://apelad.blogspot.com' // <-- again, no comma!
}

The semicolons get replaced by commatacommas (Happy, Stuart?) (except for the last one which you need to omit) and the equal signs become colons. If the properties (the things to the left of the colon) don’t have any spaces in them, you can even get rid of the quotes:

var chris = {
  hair : 'red',
  age : 32,
  city : 'London'
}

You can access the properties with object.property when they don’t have any spaces or with object[property] when they have spaces. For example:

var links = {
  'Cute Overload' : 'http://cuteoverload.com',
  'I can has cheeseburger' : 'http://icanhascheezburger.com',
  'Pencils at dawn' : 'http://pencilsatdawn.wordpress.com',
  'Hobotopia' : 'http://apelad.blogspot.com' // <-- again, no comma!
};
alert(links['I can has cheeseburger']);
alert(links.Hobotopia);

Simple if-else statements – ask and define with the ternary notation

You can shorten simple if statements dramatically. With simple I mean an if statement that assigns one of two values like this:

  var YUIguy;
  if(city === 'London'){
    YUIguy = 'Chris';
  } else {
    YUIguy = 'Eric';
  };

Again, a lot of repetition there. The ternary notation works around that problem:

var YUIguy = city === 'London' ? 'Chris' : 'Eric';

A lot of equal signs there. Maybe some parenthesis will make it clearer:

var YUIguy = (city === 'London') ? 'Chris' : 'Eric';

What’s going on here? You define the variable YUIguy and assign it a value. Then you have a statement, in this case the comparison of the variable city and if it equals to the string London (=== tests for both the value and the type, much safer than ==).

Then you ask the question if that is true or not by using the question mark. The option on the left of the colon is the answer to the question when the condition was met and the option on the right of the colon is the answer when the condition was not met. Any condition that could be true or false can go inside the parenthesis.

var direction = (x < max) ? 'left' : 'right';

Offering a fallback option with the default operator

The last thing I wanted to quickly talk about is the double pipe (||) default operator. This one is terribly useful when you want to make sure that something is set with a default value. The following construct is something that should not show up any longer:

  var section = document.getElementById('special');
  if(!section){
    section = document.getElementById('main');
  }

Again, useless repetition, as the same can be written as:

  var section = document.getElementById('special') || document.getElementById('main');

If the first is not defined, the second gets assigned as a value to section.

Thanks for your time!

I hope this helped “the average developer” to understand how you can make your JS a lot shorter without really cutting down on readability. If you want more detailed information about all these goodies, check out Douglas Crockford’s articles on the matter:

Planning JavaScript and Ajax for larger teams, equine invigorating imagery, one voice for libraries and a lot of good speakers – this was @mediaAjax 2007

Wednesday, November 21st, 2007

I’ve just been over the @mediaAjax drinks, worked through around 670 emails that accumulated in my inbox since last Wednesday and now there is some time to talk about my experience there.

First of all, here are the slides of my talk:

I didn’t cover many technical issues but instead tried to convince some people to recognize that the way you use JavaScript in your team is the most important part of development. It is not important that you write amazing code, but instead it is much more important to work smoothly together to ensure that you can deliver fast and on budget. This is the only thing that keeps us from being able to train and grow developers – we are too busy playing catch-up with estimates and deliveries. Instead we should concentrate on bringing the fun back into developing by working together rather than competing or being the “JavaScript hero” for the rest of the team.

I got some good feedback and I am happy to get more, so if you’ve been there, tell me about it. Even more importantly, if you are considering on taking on some of the ideas, I’d be interested in hearing how that went in your environment.

Generally I have to say that I enjoyed the conference a lot. I was at first disappointed by the lack of wireless but I guess that in the end it made people listen more intently to what the speakers had to say.

My faves:

  • Dion and Ben of Ajaxian covered the State of Ajax, and compared the current happenings to a wishlist they’d drafted 2 years ago. It was a fun enough keynote, but I am not too sure about some of the CSS bashing that was going on. It is very interesting to see that while CSS people want to do everything with their technology, a lot of hardcore coders just don’t grok CSS. Hey, the future is hybrids, play technologies to their strengths and allow people who care to do them.
  • Derek Featherstone’s “Real World Accessibility for Ajax-enhanced Web Apps” talked about the problems we have in creating rich client application modules like tree menus and how we fail doing them in an accessible manner. It was very entertaining and he had some good real-world photos to drive his points home. My personal favourite was the irony that the stage had a wheelchair ramp that lead nowhere because of the backdrop
  • Stuart Langridges “How to destroy the web” was as unique as he is as it was an anti-presentation as to what to do. He ran the devil’s advocate idea of us building web products in the most obtrusive and bloated manner possible as otherwise people would use all the bandwidth for looking at horse porn (his words, not mine). He had a lot of very good points (don’t do this, as it leaves too much bandwidth) and it reminded me of the Vincent Flander’s approach to teaching web development
  • John Resig’s introduction to Prototyping with jQuery showed how you can easily take a saved copy of a web site (in this case an Apple page) and enhance it with jQuery after analyzing the HTML structure. This is pretty cool for just showing a product person how a change could feel like and I’ve done it in the past with Greasemonkey scripts.
  • Alex Russell of Dojo gave us some food for thought about how libraries should become one voice and talk about the same ideas and overlap in terms of implementation to ensure we all help developers the same way instead of competing. Something I can wholeheartedly agree with.
  • Brendan Eich showed the ideas of a “new JavaScript” while Douglas Crockford explained why the “now” JavaScript is actually a cool language as it is.
  • Dann Webb showed ways how you can use JavaScript’s trickier parts like prototype and clever uses of the arguments array to enhance the language and do meta programming with it.

All in all I was happy to be part of this and I thought it one of the best conferences if you wanted to learn about JS. I did hear people complain that there wasn’t that much about Ajax, though. To me, Ajax is a methodology, not necessarily a fixed set of technologies, and to cover the whole aspect you’d need to explain both the client and the server architecture. True, this could have been done more, and I also lacked the coverage of Flash Developers as programmers that already use a lot of things that JavaScript2 is promising us.

All in all there were several great finds for me:

  • Never sit next to Bruce Lawson, Chris Willison and Stuart Langridge. It is evil but also terribly funny.
  • It is great to see that people involved in the development of competing libraries all want the same stuff and really don’t mind the success of the other competitors. Take this down, fanboys and mailing list flamers: we all want to help you and think you should use whatever suits you best, which is not necessarily our stuff.
  • The best way to recognize in your server side component if a call came from Ajax and not from a normal page submit is to check the HTTP header. Most libraries send a bespoke identifier!
  • Make sure you check if a queen has a jubilee before you go out of the train in the Westminster area.

I hope the people who went also had fun and the others will consider coming to the next conference in the London area. It is great fun and value for money.

The seven rules of unobtrusive JavaScript

Monday, November 12th, 2007

I’ve written a lot about unobtrusive JavaScript before, but I never really held a workshop about it. Well, now as part of the Paris Web Conference later this week in Paris, France I am giving one which is already sold out and I am very much looking forward to it.

As part of the workshop I prepared my materials and wanted to have a nice outline to follow. I took this as an opportunity to build up on the older materials and the outcome of this exercise is that I managed to define the rules of unobtrusive JavaScript, which are:

  • Do not make any assumptions
  • Find your hooks and relationships
  • Leave traversing to the experts
  • Understand browsers and users
  • Understand Events
  • Play well with others
  • Work for the next developer

I’ve explained them all in some detail here: The seven rules of unobtrusive JavaScript

After the workshop I will also add the code demos with some more detail, but that’ll be most probably after @media Ajax.

I hope this is helpful to you, it is creative commons, so use it for good.