Speed geek’s guide to Facebook buttons

February 14th, 2013. Tagged: JavaScript, performance

or "How to help your users share your content on Facebook and not hurt performance"

Facebook's like button is much much faster now than it used to be. It also uses much fewer resources. And lazy-evaluates JavaScript on demand. And so on. But it's still not the only option when it comes to putting a "share this article on Facebook" widgety thing on your site.

The list of options is roughly listed in order of faster (and least features) to slowest (and most features).

#1: A share link

Note that this feature has been deprecated but it still does work. And you see it all over the place.

A simple link to sharer.php endpoint is all it takes. The u parameter is your URL. E.g.:

<a 
  href="https://www.facebook.com/sharer/sharer.php?u=phpied.com" 
  target="_blank">
  Share on Facebook
</a>

The above is a hardcoded URL. You can, of course, spit the current URL on the server side. A JS-only client-side solution could be to take the document.location. You can also pop a window. And use a button, or an image. Say something like:

<button id="sharer">Share</button>
<script>
document.getElementById('sharer').onclick = function () {
  var url = 'https://www.facebook.com/sharer/sharer.php?u=';
  url += encodeURIComponent(location.href);
  window.open(url, 'fbshare', 'width=640,height=320');
};
</script>

Try it:


Method #1's performance price: none

This is just a link you host in your HTML or bit of JavaScript you can inline or package with your own JavaScript (it is, after all, your own JavaScript)

#2: Feed dialog

The feed dialog a next incarnation of the share popup.

It can also be as simple as a link, like so

https://www.facebook.com/dialog/feed
  ?link=jspatterns.com
  &app_id=179150165472010
  &redirect_uri=http://phpied.com

Try it:

Share

You need a redirect_uri which can be something like a thank you page. But instead of "thank you", you can simply go back to the article by making redirect_uri and link point to the same URL

Again, a client-only solution could be something like:

  var feed = 'https://www.facebook.com/dialog/feed?app_id=179150165472010';
  var url = encodeURIComponent(location.href);
  feed += '&link=' + url + '&redirect_uri=' + url;
  window.open(feed, 'fbshare', 'width=640,height=480');

The result is a dialog that looks like:

feed

But this feed dialog can also be a popup. You do this by adding &display=popup. This hides the FB chrome. And you can also make the "thank you" page just a simple page that closes the window.

Try it:

The result:

feedpopup

The other required thing is the app id. You need one. But that's actually cool because it has side benefits. For example better error messages for you (the app admin) that the users don't see. It also gives you a little "via phpied.com" attribution linked to the App URI which is a nice traffic boost hopefully as your sharer's friends see the story in their newsfeed or timeline and click the "via".

story

So, App ID is good, you can get one here.

Additionally there's a bunch of other params you can pass to the feed dialog to control how the story is displayed. You can provide title, description, image, etc. Full list here.

Method #2's performance price: none

Feed dialog has the same (non-existing) performance requirements as the share links. It's all inline. Any content coming from Facebook is only on user interaction.

BTW, this is the method youtube currently uses.

#3: Feed dialog via JS SDK

Now we move on from simple links and popups to using the JavaScript SDK.

First things first, you absolutely must load the SDK asynchronously. Or non-onload-blocking-asynchronously in an iframe. More on these two later.

After you load the SDK like so:

(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Then, whenever you're ready, you can make a call to get the feed dialog:

FB.ui({
  method: 'feed',
  redirect_uri: 'http://phpied.com/files/fb/window.close.html',
  link: 'http://phpied.com',
  // picture: 'http...jpg',
  caption: 'Awesomesauce',
  // description: 'Must read daily!'
});

For a working example, check this example in jsbin

The result:

jsbin-feed

As you can see, this is now a real properly resized popup. No FB chrome, nice and clean. In general the JS SDK makes everything better. But you need to load it first - the performance price you pay for all the magic.

Method #3's performance price: an async JS

Opening the feed dialog this way requires you to load the Facebook JavaScript SDK. It's one JS file with a short expiration time (20 mins). When it loads, it also makes two additional requests required for cross-domain communication. These requests are small though and with long-expiration caching headers. Since the JS SDK is loaded many times during regular user's surfing throughout the web, these two additional requests have a very high probability of being cached. So is the JSSDK itself. If not cached, at least it's a conditional requests with likely a 304 Not Modified response.

Here's the waterfall of loading the jsbin test page where you can see the JS SDK loading (all.js) and the two x-domain thingies (xd_arbiter.php)

Note that by default the JS SDK sends an additional request checking whether the user is logged in. If you don't need that, make sure you set the login status init property to false, as shown in the test page, like:

FB.init({appId: 179150165472010, status: false});

When loading the JS SDK you must absolutely make sure it's loaded asynchronously, and even better - in an iframe, so the onload of your page is never blocked.

#4: Like button in an iframe

We're coming to the Like button. There are two ways to load it: either you create an iframe and point it to /plugins/like.php or you include the JS SDK and let the SDK create the iframe. Let's take a look at the you-create-iframe option first.

The integration is straightforward: You go to the help page, use the "wizard" configurator found there and end up with something like:

<iframe 
  src="//www.facebook.com/plugins/like.php?href=phpied.com&amp;width=450&amp;show_faces=true&amp;height=80" 
  scrolling="no" 
  frameborder="0" 
  style="border:none; overflow:hidden; width:450px; height:80px;" 
  allowTransparency="true"></iframe>

You're done!

The button comes in three layouts: standard (biggest), box_count and button_count

Try it:

Standard

Box count

Button count

As you can see, you get quite a bit more features here, e.g. number of likes and social context (who else has liked) in the standard layout. Also in the standard layout you get a little comment input. You don't get one in the other layouts because there's no space in the little iframe. You define the iframe and the code inside the iframe cannot break out of it and do something wild (or useful), e.g. open a big commenting dialog. Or make the iframe bigger because the word "Like" may be significantly longer in some languages. When you "trap" the iframe in your dimensions, it stays there.

Method #4's performance price: iframe content

In this method every time someone loads your page, they also visit a page (like.php) hosted by facebook.com. Now, this page is highly optimized: it only has html, sprite and async lazy-executed JS (which doesn't block onload). 3 requests in total. Maybe some faces (profile photos), depending on the layout and whether the user's friends have liked the URL.

As you probably know, every iframe's onload blocks the parent window's onload. So, if you feel so inclined you can always do any old lazy-load trick in the book. E.g. create the iframe after window.onload, or "double-frame" it, or (for the webkits out there) write the iframe src with a setTimeout of 0.

Another thing to consider is to always load the iframe via https, so there's no http-https redirect if the user has opted to always use facebook via https.

#5: Like button via SDK

This is building on what you already know about #3 and #4: You load the SDK. You sprinkle <fb:like> (or <div class="fb-like">) where you want buttons to appear. The SDK finds these and replaces them with iframes.

<!-- all defaults -->
<fb:like></fb:like>
 
<!-- layout, send button -->
<div class="fb-like" data-send="true"></div>

If you don't need to specify the URL to like, it's the current page.

Try it:

Standard

box count

button count

This is the most full-featured button implementation. It will resize the button as required by content and i18n. It will always present a comment dialog. (When people share with their own comment, these stories do better, because it's always nice to see a friend's comment attached to a URL, right?)

The good thing about this method is that you can load any other FB plugin (e.g. follow button by just adding an fb:follow in the HTML) without re-loading the SDK, it's already there and can handle all the plugins, dialogs and API requests.

Method #5's performance price: JSSDK + iframe content

Combining the features of methods #3 and #4 also combines their perfromance impact. Again, the like.php iframe is heavily optimized and tiny. Also the SDK has a chance of being cached from the users visit on another page. And, of course, you always load the SDK asynchronously so it's impact on your initial page loading is minimal. Or load the SDK in an iframe so the impact is virtually 0.

So the total cost in terms of number of requests in empty cache view is 6. 3 from the iframe + 3 from the SDK. Full cache view should be 1 request - just the like.php frame with the current count, faces and so on.

But again, to minimize the impact, you just load the SDK in an iframe (so the whole widget doesn't block onload and doesn't SPOF) or asynchronously (so it doesn't SPOF and doesn't block onload in IEs)

Summary

# Method Features Cost
1 Share link link opens popup, no like count, no social context none
2 Feed dialog link opens page, no like count or context. You can pass customized description, image, etc for the story. Up to you to do a "thank you" page. none
3 Feed via SDK properly resized popup, JS control over the flow. No like count or context Loading JS SDK
4 Like button in your frame like count, social context, but no i18n resizing, comment option only sometimes like.php iframe (3 requests)
5 Like button via SDK All features plus proper resizing, comment dialog, easier to implement via fb:like tags in HTML like.php + SDK

I mentioned a few times in the article but let me repeat once again for the TL;DR folks. If you're loading the JS SDK, it's absolutely mandatory that you make sure it's either loaded asynchronously to avoid SPOF, or even better - in an iframe to avoid blocking onload.

Tell your friends about this post: Facebook, Twitter, Google+

58 Responses

  1. Hi Stoyan. Great post – especially relevant in light of recent third-party snippet blunders. I’d like to propose a 6th, slightly more complex, strategy, which is what we use at Trendsales: Static links combined with just-in-time async loading of the SDK.

    Basically, we built a minimal AMD module containing just the logic needed to fetch and invoke the Facebook SDK for our locale and appID on-demand.

    When a user clicks one of our ‘Share’ buttons, the AMD module is fetched asynchronously (Primer style), the SDK is loaded from Facebook, and the ‘Like’ (or whatever) method invoked. This way, we get the benefits of the lazy-loaded SDK on every page of the site with zero overhead for visitors who don’t click on a share link. The downside is a half-second-or-so delay to retrieve the module+SDK when clicking one of our ‘Share’ buttons, but we’re willing to accept that for now.

  2. [...] Speedy Website Sharing – don’t let social sharing buttons slow down your site. [...]

  3. [...] 9. Facebook Buttons and Performance [...]

  4. [...] The Speed Geeks Guide to Facebook Buttons – If you want to improve the performance of your social sharing, you may want to look at this article. [...]

  5. [...] Speed geek’s guide to Facebook buttons I hate how these social widgets are such preformance hogs. This shows some ways to make them faster. [...]

  6. Thank you for the auspicious writeup. It in fact was a enjoyment account it. Glance complicated to far delivered agreeable from you! By the way, how can we keep in touch?

  7. Great goods from you, man. I have be aware your stuff previous to and you are simply too magnificent. I really like what you’ve received right here, really like what you’re stating and the best way in which you say it. You make it entertaining and you still care for to keep it wise. I cant wait to learn far more from you. This is really a tremendous web site.

  8. Howdy, i’m sure which i spotted you frequented this internet site i really got here to go back the desire? . Now i am attempting to to locate challenges to improve my own website! Perhaps it has the sufficient to utilize a few of ones ideas!

  9. My brother suggested I would possibly like this website. He was totally right. This publish truly made my day. You can not believe simply how a lot time I had spent for this info! Thank you!

  10. Excellent things altogether, you simply earned a brand new readers. Just what could you propose in terms of a person’s send that you just made some days in the past? Every guaranteed?

  11. When driving life’s road, keep your foot on the gas, don’t drive in reverse, and don’t let speed bumps slow you down.

  12. You might definitely view your comprehension of the job you are submitting. The sector wants much more excited authors as if you exactly who aren’t reluctant to note how they consider. At all times chase your own soul.

  13. I do not even know how I finished up here, however I thought this submit was great. I do not understand who you are however certainly you are going to a well-known blogger for those who are not already. Cheers!

  14. I favor the helpful details an individual provide for a reports. Let me book mark ones web site along with examine yet again in this article typically. I will be slightly sure I might be knowledgeable many completely new products suitable below! Have fun for the!

  15. I was wondering if you ever thought of changing the structure of your site?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with
    it better. Youve got an awful lot of text for only having one or two pictures.
    Maybe you could space it out better?

  16. Hello my family member! I want to say that this post is awesome, nice written and come with approximately all important infos. I’d like to see more posts like this .

  17. Good day! This is my first visit to your blog! We are a collection of volunteers and starting a new project
    in a community in the same niche. Your blog provided us
    valuable information to work on. You have done
    a wonderful job!

  18. Oh my… I’m trying to do my website “übesocial” but all these iframe loadings and stuff are just giving me the creeps. Facebook is okay, Twitter is okay, etc. but if they add up, it’s not that awesome :(
    Anyways, you did help me a lot on my choice for solving the like button placement. Thanks a lot, you’re my hero again!

  19. Hi mates, how is the whole thing, and what you would like to say concerning this post, in my view its genuinely awesome designed for me.

  20. Hey! I’m at work surfing around your blog from my new apple iphone!
    Just wanted to say I love reading your blog and look forward
    to all your posts! Carry on the excellent work!

  21. I always spent my half an hour to read this website’s posts all the time along with
    a mug of coffee.

  22. Why users still use to read news papers when in this technological globe all is existing on net?

  23. Your posts is amazingly exciting.

  24. Your method of telling the whole thing in this piece of writing is in fact fastidious, every one be able to without difficulty understand it,
    Thanks a lot.

  25. Hmm is anyone else experiencing problems with the pictures on this blog
    loading? I’m trying to find out if its a problem on my end or if it’s the blog.
    Any suggestions would be greatly appreciated.

  26. Good blog you have here.. It’s hard to find good quality writing like
    yours nowadays. I truly appreciate people like you!
    Take care!!

  27. Tremendous issues here. I am very happy to look your post.
    Thanks so much and I’m taking a look ahead to
    touch you. Will you please drop me a e-mail?

  28. Woah! I’m really enjoying the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between usability and appearance.
    I must say you have done a superb job with this. Additionally, the blog loads very quick for me
    on Chrome. Exceptional Blog!

  29. They cannot tell the difference whether it’s another access point advertising itself as a client, they promise to the borrowers if he does not get rendered.
    McGregor also forged the signature of the official authorized to represent
    a grieved party who declares to have suffered a physical or psychological injury due to the Inland Revenue.

    How do you become a CPA?

  30. Superb, what a website it is! This web site presents helpful information to us, keep it up.

  31. This is really interesting, You are a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking more of
    your fantastic post. Also, I have shared your web
    site in my social networks!

  32. For every blogger the skill needed is more and some peoples wont know the things and search the things. These things will help them to learn how to do. Great post and thanks for sharing.

  33. This is mу firs tme go to see at here and i am genuinely happy to reazd all аt
    single plаce.

  34. Greetings! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment
    form? I’m using the same blog platform as yours and I’m having
    difficulty finding one? Thanks a lot!

  35. When you buy a car if it’s service history is available and the level
    of contamination and the value of the vehicle that far
    before switching over to its internal combustion engine noise,
    then. Only after the battery gave mankind a reliable car service jfk to brooklyn source of electricity from the” grid. Truth car service jfk to brooklyn is, for the day of the year. Even so, the chances of them being flattened by some bigger car are far more. Another thing that you want to spend the $20, 000?

  36. Nice weblog here! Also your website quite a bit up fast!
    What web host are you using? Can I am getting your affiliate hyperlink in your host?
    I desire my site loaded up as fast as yours lol

  37. Homes and outbuildings are more likely to be broken into when
    the owner is absent. In fact, the more color that is added the greater the VOC it contains but still low compared
    to the traditional varnish. Gently treat the oil or lotion
    stains and keep working them until the stain disappears, or at least become minimal.

  38. Howdy I am so thrilled I found your weblog, I really found you by accident, while I was looking on Yahoo for something
    else, Anyhow I am here now and would just like to say many thanks for a fantastic post and
    a all round exciting blog (I also love the theme/design), I
    don’t have time to read it all at the minute but I have book-marked it
    and also added in your RSS feeds, so when I have time
    I will be back to read a lot more, Please do keep up the superb
    job.

  39. If you desire, you are able to choose one of the Las Vegas hotels because the setting to your Las Vegas NV big event, reception and honeymoon.
    Just because a link is on Piratebay doesn’t imply that the users are
    getting, so because of this, the flawed data.
    We’ll start our tour at Marina Grande on the north shore with the island,
    about one third of the way in from its easternmost point.

  40. Hi, I came across your web site by means of The search engines while doing so when looking for a relevant issue, your website developed, it’s similar to superior. We have book-marked to be able to the favourites types|put into book marks.

  41. The best fails in my honest opinion here http://www.youtube.com/watch?v=Oj0l-dhuKkw.This guy is good.

  42. You’re so interesting! I do not believe I have read through a single thing like that before.

    So great to discover somebody with a few original thoughts on this topic.
    Really.. many thanks for starting this up. This website is
    one thing that’s needed on the web, someone with some originality!

  43. Heya i’m for the first time here. I found this board
    and I find It truly useful & it helped me out much.

    I hope to give something back and help others like you aided me.
    https://vimeo.com/86451295

  44. Hi! This is kind of off topic but I need some help from an established blog.
    Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about setting up my own but I’m not sure where to begin.

    Do you have any tips or suggestions? Thank you

  45. Truly no matter if someone doesn’t understand after
    that its up to other visitors that they will help, so here it happens.

  46. Highly descriptive post, I liked that a lot. Will there be a part 2?

  47. Downloading Dice entire world typically costs cash.
    I will provide you Cube Planet entire version which you can
    down load below for totally free. Indeed you will be capable to engage in Cube World in a handful of
    minutes below for free of charge, all you have
    to do is down load Dice World with the website link supplied listed here.

    We included Dice World crack so right after you install Dice Globe Alpha, you can enjoy it right away.
    Cube Planet is a 3D action RPG type match that
    is manufactured/developed by Wollay and his spouse.

    Cube Globe was began in June 2011 and now, the Alpha variation is out currently.

  48. Incredible! This blog looks just like my old one!
    It’s on a entirely different topic but it has pretty
    much the same layout and design. Wonderful choice of colors!

  49. Hmm is anyone else experiencing problems with the pictures on this blog loading?
    I’m trying to determine if its a problem on my end or if it’s the
    blog. Any feedback would be greatly appreciated.
    https://Vimeo.com/86476821

  50. Definitely believe that which you said. Your favorite justification seemed to be
    on the net the simplest thing to be aware of. I say to you, I certainly
    get irked while people think about worries that they plainly don’t know about.

    You managed to hit the nail upon the top and also defined out the
    whole thing without having side-effects , people could
    take a signal. Will probably be back to get more.
    Thanks https://vimeo.com/88582899

  51. If some one needs expert view about blogging then i recommend him/her to
    go to see this weblog, Keep up the good job.

  52. Will not put in anyy eccentric everlasting features you can’t
    change should you are not certaain about them anymore otherwise you wish to offer during
    the long term. You can work according to your pace and adaptability.
    While browsing through the internet, you will comne across many websites that are specifically
    devoted to teaching andd you can apply for them.

  53. info yang sangat menarik.
    info yang menambah pengetahuan

  54. Last but not the least, when you are direct mailing lists campaign:
    the list, plus the copy writing, etc. It must also be cleared how the
    direct mailing should be aimed at getting a positive outcome in
    the best way to do a lot of money for your marketing message?
    Or why not offer something for free right at the very beginning.

  55. I enjoy looking through a post that can make people think. Also, thanks for permitting me to comment!

  56. It may look shabby, but given the nummber of ferrari veneno
    DOM nodes in the browser. It also allows you the chance to have
    a look on these sites are the best meaning that they have outstanding
    reputations for only selling original parts iin very good or pristine condition.
    Well, I have a horrible clipping collection jujst in regular magazines
    the deformation and distortion of the ferrari veneno female body is
    amazing.

  57. Hello There. I found your blog using msn. This
    is a really well written article. I will make sure to
    bookmark it and come back to read more of
    your useful information. Thanks for the post. I will certainly comeback.

  58. Thanks for sharing your thoughhts abgout girlfriend. Regards

Leave a Reply