Loading the Facebook JavaScript SDK with jQuery

by jenny on 30 January 2011 - 01:40am in

Maybe I'm anal, but pasting the following mess in my page just after loading the jQuery library seems somehow blasphemous.

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true,
             xfbml: true});
  };
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

Here's how to do it with jQuery:

$(function() {
  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
  };

  $('body').append('<div id="fb-root"></div>');

  $.getScript(document.location.protocol + '//connect.facebook.net/en_US/all.js');
})

Thanks

Thanks, this is exactly what I was looking for.

Caching ?

IMHO, this is not a good idea, as $.getScript will skip cache by default.
Facebook SDK is a really common script, used worldwide, so using cache will speed up page loading, i would prefer :

$.ajax({
type: "GET",
url: document.location.protocol + '//connect.facebook.net/en_US/all.js' ,
success: callback,
dataType: "script",
cache: true
});

To enable cache in

To enable cache in getScript, use:

$.ajaxSetup({
cache: true
});

Reference: http://api.jquery.com/jQuery.getScript/

Bye
Andrea