YUI2: Reload Facebook, Twitter and Google+1 on dynamic pages
How to reload Facebook Like, Tweet and Google+1 buttons after only partially refreshing page content.
I recently had to retrigger Facebook Like, Twitter's Tweet button and the Google+1 button after replacing part of a pages content via an ajax call.
This solution assumes that the relevant Javascript files from Facebook, Twitter and Google are already present in the Dom, they could be hard coded or added to the Dom dynamically on page load, for example I used the YUI2 Get function:
// GET EXTERNAL JS FILES Get.script(document.location.protocol + '//connect.facebook.net/en_US/all.js'); Get.script(document.location.protocol + '//platform.twitter.com/widgets.js'); Get.script(document.location.protocol + '//apis.google.com/js/plusone.js');
In the case I was working on an call was made to the server which returned a JSON object that included the main page content as raw HTML allowing the relevant area to be replaced without having to reload the entire page, leaving areas such as the header and footer as is.
The raw HTML contained the following standard code for each of the buttons:
<!-- Facebook Like --> <fb:like href="http://www.theurltoshare.com" layout="button_count" show_faces="false" width="90"></fb:like> <div id="fb-root"></div>
<!-- Tweet --> <a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.theurltoshare.com" data-text="The text to tweet" data-count="horizontal">Tweet</a>
<!-- Google+1 --> <g:plusone size="medium"></g:plusone>
Once the page content is ready I retrigger the social buttons with Javascript like so:
// Reload Facebook
var config = {appId: 'YOUR-FACEBOOK-APP-ID-HERE', status: true, cookie: true, xfbml: true};
if (window.fbAsyncInit) {
FB.init(config);
} else {
window.fbAsyncInit = function () {
FB.init(config);
};
}
// Reload Twitter
if (window.twttr) {
twttr.widgets.load();
}
// Reload Google + 1
if (window.gapi) {
gapi.load('googleapis.client:plusone', {'callback': window['__bsld']});
}