How to add Twitter to your blog, without it hanging your site

You might be inclined to add your 'Twitters' to your blog via JavaScript - the only problem is when Twitter's traffic goes up, their servers slow down, and the net result is your web page is hanging because it's waiting to load the Twitter feed.

Some server side caching could do the trick, but it's an additional pain, so let's not bother:

Here's a fix that will allow you to keep Twitter on your sidebar using JavaScript and not worry about it hanging your blog.

As the JavaScript badge examples show you can use a JSON feed of your 'tweets' to plug in to your page. Once the JSON is loaded, it calls the callback method: 'twitterCallback'.

We're going to wait until the page has loaded before we pull in the Twitter feed - if Twitter is fast, the reader won't notice any difference, but if Twitter is slow, the page won't hang, and Twitter will load in it's own time.

window.onload = function() {
var url = 'http://www.twitter.com/t/status/user_timeline/rem?callback=twitterCallback&count=1';

var script = document.createElement('script');
script
.setAttribute('src', url);
document
.body.appendChild(script);
}

Obviously change the URL to your own timeline - the user ID can be seen in your own personal Twitter RSS feed - or in the code for the JavaScript badge.

I prefer not to overwrite the .onload event, so I would use jQuery to add to the onload events and change

window.onload = function() {

...to:

jQuery(function() { ...

But you can use whatever library or 'polite' onload handler you want. However, if the Twitter code is the only JavaScript on your page - you can keep it as is.

0 comments:

Bookmark and Share

Post a Comment

 

WEB CREATION Copyright © 2009 Blog is Designed by Suvanno Tharu Sponsored by Hitsweb Pvt.Ltd