Add Twitter to your blog (step-by-step)
Hotlink from Google
<script src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js"></script>
Download to self host
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“. This can also be a list (in the format of user/list-name, ie. rem/conferences) or a hash tag.
- 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
lielement. 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_str%/">%time%</a>'
});
Template variables
All variables should be wrapped in % symbols (see the above example).
- text – the actual status message
- id_str – id of status message (note that id was used before, but for the ids to be correct, you need to use id_str)
- source
- time – relative ‘friendly’ time
- created_at – raw time
- user_name – real name
- user_screen_name – username
- user_id_str
- 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 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_str%/">%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.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)


Thank you very much, it worked really well!
That’s a clever way to work around the AJAX restriction on loading data from a different site. I’ve been working on a twitter proxy to run on my site so that I could use ajax commands to get twitter data. I like this solution much better.
When I was working on my code, I was having problems with my browser caching the twitter data. It would only update about once an hour or so. Have you seen that issue with this code?
You don’t mention licensing of this code anywhere. Copyleft? MIT-style? GPL? Public Domain? Hopefully, one of those.
Hi Remy,
This is a really neat piece of code – thank you. I’m using it with RapidWeaver, and it seems to not hide the progress indicator once the tweets have loaded. Sadly my JS knowledge is, well, lacking. Any pointers? Thanks! Nik
[...] + Add Twitter to your blog: um script para adicionar o Twitter no seu blog, diferente do badge oficial. [...]
@KennyH – on the browser caching you can try one of the following two to get around the problem:
1) Cache busting – add a random number to the end of the requested URL – then the browser won’t cache it, e.g.
var cb_url = url '&cb=' Math.random();2) Use POST instead of a GET on the request. The browser can’t cache POST requests so this also gets around the problem. However, with a POST you need to ensure the server will still serve up the page properly – but it’s relatively easy to test.
On the license on the code – I’ve updated the file with a Creative Commons ShareAlike license – basically: help yourselves.
@Nik – If you drop me an example link I’ll take a look at fixing the problem.
http://www.nikfletcher.com/20 is the URL. There’s an assortment of Scripatculous scripts in there as well, but when I removed all the Javascript except twitters.js, it still appeared to not hide the loading animation. Thanks!
@Nik – my fault – there was a typo in the example I provided (typical). The parameter ‘clearContent’ should read ‘clearContents‘. That will fix it.
I’ve also just released a new version the twitter.js that uses a better load event, i.e. if fires before the images are loaded rather than waiting.
Fantastic. I’ve now started it using it on my ‘live’ site.
Many Thanks!
-N
great work, thx
is this script still working? i cant seem to make it work, and i cant see it working at nikfletcher’s page either…
@chrischen – good point! I’m looking in to it now…
Hi all,
It looks like the URL that was in the twitter plugin I wrote was recently depreciated by Twitter. I’ve now updated the plugin and it’s working again.
Good catch chrischen – cheers.
[...] twitter plugin has just been upgraded to (optionally) search for links in the twitter text and activate them as [...]
This is exactly what I’ve been looking for. Thanks for making this available!
How can I format the text, though? I’d like to make the, “about 15 minutes ago” text italicized and a different color so it stands out from the twitter text. I looked around in the js file, but I’m not a programmer and couldn’t figure it out. Thanks for your help!
Open the twitter.js file in a text editor. You can edit the status messages.
For example, I translated them into Danish so they would fit on my site:
Yeah, this is perfect!
I’d also love to have the ability to format the text. Is there away to append a class to the generated span tags so that they are style-able? Like Tim, I’m not a programmer but assume something like this, or easier, should work.
Nice code, hats off to you my friend. Thanks for sharing this tutorial.
I can’t seem to get mine to work: http://www.rapidmac.com
I looked through the JS file and the page code, but I can’t figure out what could be causing the problem.
Never mind I fixed it. However, is there any (relatively easy) way to style the times text so it is different from the tweet text?
I have a group blog, 5 members, and was wondering if there was a way to send multiple ids and get 1 tweet per user. I tried multiple copies of the .js and setting divs as twitters1 twitters2 …. but that didnt work, I either got the only the last one to show up, or they others showed up but with the last person’s prefix so they were not identified correctly.
[...] Twitter’s JavaScript blog plugin works in exactly the same way. You create a function to handle the data from Twitter, and insert a script tag. Once the script is inserted, it calls the function passing the Twitter data as a JSON object. [...]
Great code! How do I remove the bullet before the text?
Yes, I’d also like to figure out how to remove that pesky bullet…thanks in advance
Remove the bullet with css:
I did the css trick with my blog, http://natenews.tumblr.com. Is there a better way to re-align it after the indent besides adding: margin-left: -40px; ?
Perfect! Thanks Remy! We need to make this a WordPress plugin!
This is great! But I have a question: is there a way to DO NOT SHOW the REPLIES? I thought about the clearContents, but I don’t know if this is possible… =]
Thank you! =]
@Borbs – do you mean that out of a list of, say 10 tweets, you want to ignore any that start with @myfriend?
If so, I’m in the process of doing some small upgrades to the script and I can include this feature as an option.
@Borbs – I’ve updated the twitter.js script to also support an
ignoreRepliesoption.I’ve also fixed HTML entities from appearing in the tweet and wrapped each logical block in a span with it’s own class name:
Hi remy, thanks for the great script and also taking the time to help individuals like me implement it to my site.
Im trying to work out how to format the text to be trebuchet Ms bold 7pt White whn it shows the twitters.
i promise i have tried but cannot get the css to work, i have absolutely no idea how to write css and link it to the Twitter result.
Can you help please
thanks
Tommy
@Tommy – if you want all the text to be bold and white – this will do (assuming you’re using ‘twitters’ as the ID on the container):
If you wanted to target specific blocks of content, such as just the time and make it, perhaps blue (you get the idea):
Remy, i will try this right now thanks for a very very prompt reply.
T
Hi Remy, can i just say wherever you are in the world, thank goodness. great help for a novice with pretty rudimentary coding skills. Your help was second to none and your script rocks. thanks so much for taking your time out and helping another Webhed.
you truly are a decent fella.
Best Regards, Cheers!
Tommy
http://www.innocentinteractive.com (My portfolio)
Probably no issue with the script at all but I’m having trouble with 2 pages acting differently:
http://ramchandra.me.uk/blog/
http://ramchandra.me.uk/about/
I’ve followed the exact same steps & in firefox — spot on!
in IE however I get “Operation Aborted” message on the Blog page (not on the About) .. very weird. I’ll update to your latest & greatest script & see if that helps.
Whatever change you made in that release — fixed it :) Yay!
Thanks a lot, Remy. This is a really cool script.
You can see it in my link: http://jayrobinson.name
Or check out my other site, a travel blog while I’m abroad: http://nopeanutbutter.com
Any way to pull the tweets of my friends as well as my own like Twitter does with one of their flash options?
Twitter
I have “Twitterlise” this site (via Remy Sharp), my WordPress site (via Twitter for WordPress), my Facebook profile (via Twitter Application For Facebook), my Windows Live Messenger (via Twessenger) and my Messenger Plus! Live (via Twit4Li…
Hi, I am currently using your script and I love it. Definitely the one after looking around for hours. I have a question. Where in the .js file could I put the date in parentheses?
@Sarah + @Hammer – I’m going to release the new version of the script today.
New features include, the ability to include friend’s tweets, use of variables in the text (i.e. in the prefix you want the appropriate name to appear), and the biggest change – template driven output.
This will give you complete control over how the twitter appears, and in your case Sarah, you’ll be able wrap the date or do as you please.
[...] Add Twitter to your blog (step-by-step) (tags: twitter javascript web web2.0 blog programming wordpress) [...]
Many, many thanks – this is JUST what I was looking for :)
With the addition of friends and the template driven output this is really quite fantastic.
I love the script! It’s just what I was looking for. Thanks for sharing! Brilliant work!
Kind regards.
@Piotr – I see from your web site you’ve reverted back to 1.2 of Twitter.js. Is the new ones not working for you? If you have an example, I don’t mind taking a look.
Remy, this is a newbie question. Where do I upload the script to? The theme root or the website root?
@Koka – it doesn’t really matter, but if you want to keep things really simple, stick it in the root of your web site (usually htdocs) and refer to it as
/twitter.jsAbsolutely brilliant. The solution to a problem I’ve had for a good while.Thank you so much!
[...] Tools for regular Twitter digest posts and built-in posting from WP, and a combination of twitter.js and the Twitter Widget for my sidebar [...]
Hey, thanks for this. However, I don’t want the resulting information to be within ul and li tags. I’m only telling the function to give me 1 update, and the reason is I want to put it within a p tag, but it keeps giving me an li tag no matter what. I’ve spent two hours trying to figure out how to do this to no avail and I’m going insane. I would really appreciate if you could help me with this, please.