Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).

2006-11-22

Loading Javascript widgets asynchronously

Lots of sites now provide javascript widgets. Typically, they ask you to paste something like this into your blog sidebar:

<script src="http://www.flickr.com/fun/zeitgeist/badge.js.gne" type="text/javascript"></script>

This bit of code tells browsers to go off to www.flickr.com and fetch the badge.js.gne file. There's a problem with doing it this way: if www.flickr.com is running really slowly, the file might take quite a while to download, and until it's downloaded, the rest of your blog won't display.

I wrote about this problem back in June, and suggested a way around it - a hack that you could use to capture the HTML written by the included Javascript, and drop it into a div. This was better, but still not perfect. It required splitting the code to paste into your blog into two sections: one to go in your sidebar, and one in your footer. Also, it was a bit of a hack.

Here's the new and improved version, which is part of the current development version of PeopleAggregator. It's one chunk of HTML/Javascript that you can drop straight in your blog, that will show a placeholder div at first, then download the content once the page is finished loading.

<div id="pa_widget_8113571">[Loading PeopleAggregator widget ...]</div><script language="javascript">var widget_8113571=window.onload;window.onload=function(){var s=document.createElement("script");s.type="text/javascript";s.src="http://www.peepagg.net/badge.php/jsdiv/18/show/default/div=pa_widget_8113571";document.getElementsByTagName("head")[0].appendChild(s);if(widget_8113571)widget_8113571();};</script>

And here's how that looks in practice (a little broken in Firefox, I'm afraid!):

[Loading PeopleAggregator widget ...]

How it works: it hooks window.onload to find out when the page has finished loading, at which point it adds a new <script> element into the header of the page, which fetches the widget Javascript. The Javascript is different from before; instead of using document.write, it inserts the widget HTML straight into the DOM using document.getElementById, using the ID specified at the end of the URL. 8113571 is a random number, just in case you have multiple widgets or other sites start using this code.

I'm just about to implement multiple widgets, so a single user on a PeopleAggregator install can configure several widgets. You could have one for each of your blogs, or perhaps more than one on a blog, if you wanted to show your friends at the top of your sidebar and your blog posts in the main body area. And of course, because of the new trick, it won't slow down your page load, even if the PeopleAggregator server bogs down or crashes.

... more like this: [, ]