开发者

Twitter widget callback

How do I call a callback when a Twitter widget is rendered?

Using the code they provided:

TWTR.Widge开发者_开发技巧t({data: something}).render().setUser('me').start();

Twitter has notoriously spotty service and frequent long load times. How do I add a callback on loading of the TWTR widget, so I can show my users a loader in the meantime?


I had to hunt down the author of the library on Twitter, but there is a ready callback: E.g.

new TWTR.Widget({
  id: 'twitter-feed',
  version: 2,
  .
  .
  .
  features: {        
      scrollbar: false,
      .
      .
  },
  ready: function() { 
    jQuery("div#twitter-load").remove();
  }
}).render().setUser('me').start();


The widget has a _rendered property.

I made an example on jsfiddle. Note that there is no callback, you have to poll it to check if it has rendered. Also, you have to assign it to a variable when you create it, so you can access the _rendered property.

I found this by jsbeautifying the script, so it might not be 100% trustworthy and definitely not supported.


Using ash's "ready" function discovery, I needed to add some polling so that I would only remove the loading message if any tweets actually loaded. To test this, I would add the following to my hosts file to simulate an error fetching the tweets:

127.0.0.1    api.twitter.com

Note that my polling only executes 10 times with an interval of 200ms. This is because I don't want the code to poll indefinitely when the tweets seem to load within the first 2 seconds (if they are going to load at all). You can tailor these values to suite your situation.

function pollForTweets() {
    if (jQuery("div#twitter-feed").find("div.twtr-tweet").length > 0) {
        jQuery("div#twitter-load").remove();
        return;
    }

    pollForTweets.pollCounter = pollForTweets.pollCounter || 0;
    if (pollForTweets.pollCounter < 10) {
        pollForTweets.pollCounter++;
        setTimeout('pollForTweets()', 200);
    }
}

new TWTR.Widget({
    id: 'twitter-feed',
    version: 2,
    .
    .
    .
    features: {
        scrollbar: false,
        loop: false,
        live: false,
        behavior: 'all'
    },
    ready: function () {
        pollForTweets();
    }
}).render().setUser('twitter').start();


In addition to the ready() callback and _rendered property (thanks jasie and harpyon), there are a swathe of other useful, undocumented properties also. Eg. results (an array, thus results.length), and showedResults (another array, subset of result).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜