Check out my latest project: Full Frontal JavaScript Conference

Add Twitter to your blog (step-by-step)

Update - updated 25-Aug 2009

You can now directly hotlink from Google to remain up to date without having to change your script, see code below.

Hotlink from Google

<script 
  src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js"
  type="text/javascript">
</script>

Download to self host

Download latest Twitter.js

Following on from how to add Twitter without hanging your blog, as requested, here is a step-by-step guide to adding Twitter to your blog without it hanging your web site.

Below is a working example of loading twitters after the page has completed, thus preventing the whole page from locking up (notice that the spinner will continue until the twitters are loaded) - based on my tweets from myself:

Please wait while my tweets load

Using my twitter.js script.

Options

The function tags the following parameters:

  • CSS id of target element
  • Settings object (details below)

Settings object:

  • id: your screen name on Twitter, for example mine is "rem"
  • count: number of twitters you want, defaults to 1.
  • clearContents: if you have content in the container you may want to clear it. Defaults to true.
  • enableLinks: true/false - scans the tweet for a link and makes it clickable, includes @replies and #hashtags, by default is true.
  • ignoreReplies: true/false - skips over tweets starting with @. If requesting 1 tweet, and this flag is set, behind the scenes it will request 2 in case the first starts with @ - but if the 2 most recent are replies, nothing will be shown.
  • currently disabled withFriends: true/false - whether to include friends tweets. Defaults to false.
  • template: the HTML template to use within each li element. See below for template variables.
  • prefix: if not using a template, you can use this. If you want to prefix each twitter, add here, e.g. 'Remy said'. Note that you can use template variables in this field.
  • timeout: Number of milliseconds before triggering onTimeout. If onTimeout is set, timeout defaults to 10 seconds.
  • onTimeout: Function to call when timeout is reached. Context is set to HTML element tweets were going to be inserted into.
  • onTimeoutCancel: true/false - if not set, the timeout can trigger, but then the Twitter script could complete and override the cancel. To avoid this, set onTimeoutCancel = true. Defaults to false.
  • newwindow: true/false - if set to true, all links in tweets (and otherwise) will open in a new window. Defaults to false.
  • callback - Function to call when the twitter render is completed. Doesn't fire if the script times out.

For example:

getTwitters('tweet', { 
  id: 'rem', 
  count: 1, 
  enableLinks: true, 
  ignoreReplies: true, 
  clearContents: true,
  template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
});

Template variables

All variables should be wrapped in % symbols (see the above example).

  • text - the actual status message
  • id - id of status message
  • source
  • time - relative 'friendly' time
  • created_at - raw time
  • user_name - real name
  • user_screen_name - username
  • user_id
  • user_profile_image_url - avatar
  • user_url - home page
  • user_location
  • user_description

Container HTML

You need to insert a holder element for the twitters to go in to. In the example above, I've included some 'waiting to load' content - but you don't have to.

Here's what I did:

<div id="tweet">
 <p>Please wait while my tweets load <img src="/images/indicator.gif" /></p>
 <p><a href="http://twitter.com/rem">If you can't wait - check out what I've been twittering</a></p>
</div>

Here are some more progress indicators.

If you include contents inside the holder div, then you'll need to set the 'clearContents' flag.

Add the script

You can download the twitter.js script or you can hotlink directly from the Google code repository (as seen in the example below).

Add the following code within the head or (best at the bottom of the) body tag:

<script 
 src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js" 
 type="text/javascript">
</script>
<script type="text/javascript" charset="utf-8">
getTwitters('tweet', { 
  id: 'rem', 
  count: 1, 
  enableLinks: true, 
  ignoreReplies: true, 
  clearContents: true,
  template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
});
</script>

(this example will generate my twitter status in quotes on a single line with the 'ago' linkable back to the original twitter post)

Note that the getTwitters function will execute after the page has been loaded by your browser. It will fire once the DOM is loaded but before images are loaded.

Styling

If you don't use a template, then the HTML is generated for you.

Each block of text is contained with in a span and includes it's own class, e.g. the HTML generated would look like this:

<div id="tweet">
  <ul>
    <li>
      <span class="twitterPrefix">Remy said: </span>
      <span class="twitterStatus">I just had a bizarre spaces moment - moving my cursor to the bottom of the screen switched space - annoying if it hadn't just gone away.</span>
      <span class="twitterTime">20 minutes ago</span>
    </li>
    <li>
      <span class="twitterPrefix">Remy said: </span>
      <span class="twitterStatus">Great quote - Michael J Fox: "my happiness grows in direct proportion to my acceptance, and in inverse proportion to my expectations."</span>
      <span class="twitterTime">7 days ago</span>
    </li>
  </ul>
</div>

So each block of content is targetable using CSS to style the way you wish.

Comments, feedback or suggestions will be more thank welcome.

405 Responses to “Add Twitter to your blog (step-by-step)”

  1. Alert: Your link to AJAX indicators is a porn-spam site.

    Not that I don't enjoy porn, but, you know, I was also interested in AJAX indicators.

  2. Good catch! Duely updated to a site that hasn't been hijacked by anti-spinner campaigns! :-)

  3. Remy, this is awesome stuff. One question though - any thoughts as to why invoking this for multiple twitter feeds doesn't work in IE7 (only one instance loads) or *shudder* IE6 (no tweets ever load)? Even on this very page, I can only get one set of your tweets to load.

    Everything is beautiful on Firefox; I just have to remember to check IE more often.

  4. Hi, this is js exactly what I'm looking for but I'm not able to get it running.
    I have the .js and css-file in place but can't figure out how to place the call in the template and in a page itself (I'm using inline js for WordPress for that matter).

    Any help appreciated.

  5. @Brian - Thanks for spotting the bug. It's now fixed in IE. Cheers!

    @Thomas - if you've got an example I'll take a look for you. Drop me a link on this blog if that's okay.

  6. @Remy here is the link http://randgaenge.net/

  7. Fix worked perfectly Remy. Thank you much, and best of luck on your ride.

  8. This is fantastic, I was just about to hack in a few additions to an older version of this when I found it had been updated. Couple of features I'd like to see are:
    Detecting links (to any site) and writing a link tag around them;
    Correcting grammar by adding a full stop to the end of any status without a punctuation mark.
    These could both the turned on by options.

  9. @Hugo - it's actually in the documentation, but not in the source, but try: enableLinks: true in the config and it'll make links clickable.

  10. @Remy - Ah yeah, I realised this about 5 mins after pressing submit on my comment, it's great! Also I created a prototype function for correcting any lack of trailing grammar, it's as follows:

    String.prototype.grammarify = function() {
      if (!( /W$/.test( this.replace(/^s+|s+$/g, '') ) )) {
        return this + '.';
      }
    };
  11. Also I noticed that if you have ignoreReplies set and your recent tweets are all replies (more than 1) then nothing is displayed. It's easily fixed by tweaking the script, but maybe an option for this?
    By the way, ignoreReplies is a great feature!

  12. @Huge - I don't know why I didn't do that earlier. I thought I'd have to keep re-requesting, but I changed the code a while ago to limit based on the count passed in. Anyway, grab version 1.10 and it should fine a tweet amongst the @replies.

    Note that the max it can get is 20 tweets, so if the last 20 are all @replies, it won't show anything.

  13. Sorry, but after lot or hour spend to debug it, i can't make your script working on my site.

    I've been make a test page espacially without others scripaleous and prototype.. not working:
    http://2009.mat.be/test.asp

    It still loading

    Can you help me?

    Mat

  14. @Mat - you've not specified the element ID correctly. Check out the two lines that are highlighted:

    http://codedumper.com/atasi#8,13

    It should read:

    getTwitters('twitters', {
  15. I'm feeling so stupid... lol But for my defense, it's written nowhere...

    I've now anothers problems:
    - Preload-test don's disapear: http://2009.mat.be/test.asp
    - There is a bullet before and i've not specified that in templace
    - on the true page (not the test one) twitters state is loaded after google syndication. Can i load it before?: http://2009.mat.be/content.asp?id=cv

    Regards,

    Mg

  16. @Mat to try and answer your questions:

    1. The documentation is both in the code (see @params) and as the very first thing on this page - but not to worry ;-)
    2. The test page looks like it's change - there's only a couple of divs in it now.
    3. That's the <li> element. You'll need to style that with CSS, something like ul { list-style: none; }
    4. No - I suspect not. What's happening is Google's ads are loading at the page loads. If Google were to go down (highly unlikely) then it would hang your web page. This is the crux of my script. Twitter does go down, and if you have the traditional script they offer, when Twitter is down, it'll hang your web page from loading too. So, my Twitter script waits until the DOM has finished loading, then tells the page to load the tweets.

    I hope that all helps. Cheers.

  17. I can't seem to get my Twitters to load. If you could look at my site and tell me what I'm missing, I'd really appreciate it!

  18. Please check here:

    it does not disaeper:
    http://2009.mat.be/content.asp?id=welcome&theme=1

  19. @HelloKit - please see Mat's comment above your own.

    @Mat - you've added the property clearContent when it should be clearContents

  20. Wow, I'm stupid. Never mind. It was the container ID.

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight