As anyone who’s used it knows, the standard JS Twitter Widget document.write-s itself into the page by default. This obviously sucks because a) you have to have the JS for it mixed up in your content, which in turn means b) if it hangs for some reason, all content after the widget is held up.

Asynchronous loading

The way round that (as others have found out before me) is to use an undocumented API argunment “id”, which defines the ID you would like the Widget written into. This in turn allows you to call the widget code as a function on, for example, JQuery’s document.ready, shown below, which in turn allows you to load Twitter’s widget.js at the bottom of the page, even using $.getScript() to delay it even further:

// Note: This function should not be global like this in real world use 
function renderTwitterWidget(){ 
	new TWTR.Widget({ 
		id: 'iTwitterContainer', 

		// ...Rest of normal Twitter widget code... 

	}).render().start(); 
} 

$(function () { 
	$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){ 
		renderTwitterWidget (); 
	}); 
});

There: Fail Whale proof.

Asynchronous reloading

Thing is the design required that the user be able to refresh the widget with a different search term. The above code can do that, with a couple of additions:

  1. Add the search term as a parameter to be sent to the function.
  2. Use the .stop() method (found by searching the Twitter Widget source) to kill off previous instances’ setTimeouts, which otherwise carries on populating your container with the previously chosen search term(s).
// Note: Again, this variable and function should not be global in real world use: 
var twitterWidget = false; 
function renderTwitterWidget(searchString){ 
	if (twitterWidget){ 
		twitterWidget.stop(); 
	} 
	twitterWidget = new TWTR.Widget({ 
		id: 'iTwitterContainer', 
		search: searchString, 

		// ...Rest of normal Twitter widget code...
 
	}).render().start(); 
} 

$(function () { 
	$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){ 
		$('.iTwitterLink').click(function(){ 
			renderTwitterWidget("New Search Term"); 
		}); 
	}); 
});