Skip to content

Instantly share code, notes, and snippets.

@Jpunt
Forked from remcoder/facebook.loadonce.js
Last active December 17, 2015 02:08
Show Gist options
  • Save Jpunt/5533079 to your computer and use it in GitHub Desktop.
Save Jpunt/5533079 to your computer and use it in GitHub Desktop.
/*global $ */
/*
_______ _______ _______ _______ _______ _______ _______ ___ _
| || _ || || || _ || || || | | |
| ___|| |_| || || ___|| |_| || _ || _ || |_| |
| |___ | || || |___ | || | | || | | || _|
| ___|| || _|| ___|| _ | | |_| || |_| || |_
| | | _ || |_ | |___ | |_| || || || _ |
|___| |__| |__||_______||_______||_______||_______||_______||___| |_|
___ _______ _______ ______ _______ __ _ _______ _______
| | | || _ || | | || | | || || |
| | | _ || |_| || _ || _ || |_| || || ___|
| | | | | || || | | || | | || || || |___
| |___ | |_| || || |_| || |_| || _ || _|| ___|
| || || _ || || || | | || |_ | |___
|_______||_______||__| |__||______| |_______||_| |__||_______||_______|
Facebook.loadOnce is a simple wrapper for the official Facebook JS SDK for promise-based lazy-loading.
1. Whenever you want to for example initialize a Facebook button:
Facebook.setCulture("nl-nl");
Facebook.loadOnce().done(function (FB) {
FB.XFBML.parse();
});
2. When you call loadOnce again it will NOT load again but with it WILL trigger
the done handler immediately:
Facebook.loadOnce().done(function (FB) {
FB.XFBML.parse();
});
Note that setCulture() should be called once, before the first time loadOnce() is used.
If you forget this (or do this twice), an exception will be thrown.
3. Also, since Facebook.loadOnce returns a Promise object, you can use the full
Promise API, including chaining asynchronous calls:
Facebook.loadOnce().then(function () {
return $.post("/dummy", { some: "data" });
})
.then(function() {
return $("#dialog").animate({ opacity : 1});
})
.done(function () {
console.log("all done!");
});
*/
var Facebook = (function() {
"use strict";
var _loadingStarted, _culture;
window.fbAsyncInit = function() {
if (window.FB)
_loadingStarted.resolve(window.FB);
else
_loadingStarted.reject(); // shouldn't happen! probably means a bug in FB
};
function _load() {
_loadingStarted = $.Deferred();
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/"+_culture+"/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
}
return {
setCulture: function(culture) {
if (_culture)
throw new Error("Culture cannot be changed after first set");
_culture = culture;
},
loadOnce : function() {
if (!_culture)
throw new Error("Culture should be set before first load");
if (!_loadingStarted)
_load();
return _loadingStarted.promise();
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment