Monday, January 5, 2009

Twits.js

I was working on my Tumblr blog this weekend and decided the stock JavaScript Twitter widget supplied by Twitter wasn't sufficient to my needs. For starters the blogger.js widget code is served from their servers so you can't edit it, it's minified so you can't read it, and they do a crap job of making it accessible via CSS by using things like inline styles to set font-size on the date tag.

So I wrote my own. Lots of other people have done similar stuff, so I reused a lot of code from the internets. One awesome trick I found was to insert a script element into the DOM that loads the JSON directly from Twitter via the src attribute. That avoids the restrictions on cross-site Ajax calls (which was the first method I tried). I also used some clever String extensions to parse user-names, URLs and Twitter hash-codes into embedded links, and extended the JavaScript Date class to provide relative time strings.

The main difference between all the other Twitter widgets out there and mine is custom configuration via an options hash. Since the widget loads the Twitter feed on the window's load event, the user can override the default options in an inline script block after loading the script file to set their username, the number of tweets to download, and most importantly a custom render function.

And that's the best thing about JavaScript -- the ability to pass functions around as objects makes the code malleable. If you want to add your own methods to JavaScript's String object, it's right there for you to play with. In this case, you can rewrite the TwitOptions.render function to use whatever fields from Twitter's JSON object you care to. Want to display your user icon? Go for it. Want to add custom class tags and CSS the bejeezus out of your feed? It's all you, baby.

I put the code up on my GitHub account. By the way I take back all the mean stuff I said about GitHub yesterday. Once you get your junk set up properly, it is pretty sweet. IYI the instructions on how to do that on a Mac are here.

Next up: I want to make it possible to configure it to fetch other feeds besides a single user's Tweets. And maybe add the option to display both your feed and your friends' feed on separate tabs. Really it wouldn't be that hard to customize it to fetch other JSON or XML feeds so maybe I'll do Flickr and Last.fm mods next weekend.

No comments:

Post a Comment