最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to delay a javascript function until after Jquery & Facebook are both loaded? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 5

Is 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

发布评论

评论列表(0)

  1. 暂无评论