Jquery provides a very convenient way to delay executing code until the DOM is fully loaded:
$(function() {
dom_is_loaded();
});
The Facebook Javascript SDK, when loaded asynchronously, provides a similar mechanism:
window.fbAsyncInit = function() {
fb_is_loaded();
}
What's the most elegant way to delay code from running until the DOM and Facebook's SDK have both fully initialized?
Jquery provides a very convenient way to delay executing code until the DOM is fully loaded:
$(function() {
dom_is_loaded();
});
The Facebook Javascript SDK, when loaded asynchronously, provides a similar mechanism:
window.fbAsyncInit = function() {
fb_is_loaded();
}
What's the most elegant way to delay code from running until the DOM and Facebook's SDK have both fully initialized?
Share Improve this question asked Apr 2, 2011 at 17:44 LeopdLeopd 42.8k32 gold badges135 silver badges172 bronze badges4 Answers
Reset to default 5Is there a reason why just doing
window.fbAsyncInit = function() {
$(function() {
both_loaded();
});
}
doesn't work?
Why not:
var jq_ready = false, fb_ready = false;
function bothReady(){
...
}
$(function() {
dom_is_loaded();
jq_ready = true;
if(fb_ready){
bothReady();
}
});
window.fbAsyncInit = function() {
fb_is_loaded();
fb_ready = true;
if(jq_ready){
bothReady();
}
}
I think this is cleaner than setting an interval and will handle either event happening first.
Probably set a flag in your fbAsyncInit
function and check it in the jQuery load:
$(handleLoad);
function handleLoad() {
if (!facebookLoaded) {
setTimeout(handleLoad, 10); // Or 100 or whatever
}
else {
// You're good to go
bothLoaded();
}
}
I expect there's already some global you can check for whether Facebook is loaded (I haven't used the Facebook API). If not, you can use your own flag (ideally not a global):
(function() {
var fbLoaded = false;
window.fbAsyncInit = function() {
fbLoaded = true;
};
jQuery(handleLoad);
function handleLoad() {
if (!facebookLoaded) {
setTimeout(handleLoad, 10); // Or 100 or whatever
}
else {
// You're good to go
bothLoaded();
}
}
})();
You might want to check out this explanation
http://pivotallabs./users/jdean/blog/articles/1400-working-with-asynchronously-loaded-javascript