I was looking at the Digg source code the other day and, I’ve gotta say, mega-props to the developer of their javascript. The traditional rule in web development has become, “Put your Javascript at the end of your page.” That way, all of the DOM objects you might refer to are guaranteed to be present when you start referring to them. This had been a chronic problem in web development, associated with much pulling of hair and gnashing of teeth. The more modern way is to load your scripts up front, but use jQuery’s $(document).ready(...) method to ensure that nothing would run until your DOM tree was loaded. You might still have to wait on media assets (you used to be able to say “images”, but with HTML5 media assets include sound and video), but the DOM will be there and ready. You’ll be free to set up onload events to the media assets. The $(document).ready(...) technique ensures that your javascript will run correctly but it still has one classic problem: download delay. If you want an anchor to do something more than just be a link when you click on it, you’ll have to live with the chance that the user will click on it before the javascript has run and it will just be a link. Digg doesn’t live with that. Instead of using $(document).ready(), they do something much more clever. In the header of their HTML document, they create unique event names that signal when some part of the page has been handed to the browser. You can do this with jQuery, which lets anything at all be an event. Let’s say you have an anchor that you want to do something funky when you click on it, something Ajaxy. First, in a javascript library that you load in the header, you define the function:
function dosomethingfunky() { /* ... do something funky with $(this) ... */ }
Then you bind it (note the completely custom event name):
$(document).bind('somethingfunky_ready', dosomethingfunky);
And finally, in the body, when the anchor has been loaded into the DOM, you trigger the set-up right there:
Funk Me!
Now that’s cool. Your race condition window is down to milliseconds; the event handler is probably set up even before the browser has a chance to render the object. Yes, there’s a price: your page is littered with triggers and unobtrusiveness is a thing of the past. But if you need this kind of set-up and performance, this is how it’s done, aesthetics be damned.
This entry was automatically cross-posted from Elf's technical journal,
ElfSternberg.com