29a.ch experiments by Jonas Wagner

Loading twitter widgets asynchronously using yepnope

Written by

Twitter widgets block the loading of your page by default. So if twitter goes down it will take half of the internet with it. That of course is fail! So let's use yepnope.js to decouple them from your page.

Starting position

<body>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="29a_ch">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'search',
  search: 'rainbow'
  // ...
}).render().start();
</script>
</body>

Twitter button

The twitter button is actually implemented nicely using data attributes and progressive enhancement. This makes life easy for us.

<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="29a_ch">Tweet</a>
<script src="yepnope.js"></script>
<script>yepnope('http://platform.twitter.com/widgets.js');</script>

As you can see loading the twitter button with yepnope is trivial but you get some flickering. Let's improve that with a stylesheet

a.twitter-share-button { display: block; width: 110px; height: 20px; visibility: hidden; }

This will preallocate the space needed for the twitter button. You might need to tweak it depending on the button you have chosen. Making the button fade in with css3 transitions would be another option.

Twitter Search Widget

The twitter search widget is a bit more problematic as it is using document.write(). I really wonder why they got the button so right and the other widgets so wrong. BOOOOH! If you look at the source you will find something interesting though:

if(!o.id){document.write(

It looks like somebody at twitter was aware of the fact that using document.write isn't a good idea and provided a way around it. He just didn't clearly document it. So let's use the id option to fix our problem.

<div id="twat"></div>
<script src="yepnope.js"></script>
<script>
function twatr(){
    new TWTR.Widget({
      id: 'twat',
      version: 2,
      type: 'search',
      search: 'rainbow'
      // ...
    }).render().start();
}
yepnope({load: 'http://widgets.twimg.com/j/2/widget.js', callback: twatr});
</script>

I hope you can now sleep well at night - without nightmares of fail whales (just ignore the fact that you are using an undocumented feature).

comments powered by Disqus