简体   繁体   English

如何延迟javascript函数,直到Jquery和Facebook都被加载?

[英]How to delay a javascript function until after Jquery & Facebook are both loaded?

Jquery provides a very convenient way to delay executing code until the DOM is fully loaded: Jquery提供了一种非常方便的方法来延迟执行代码,直到DOM完全加载:

$(function() {
    dom_is_loaded();
});

The Facebook Javascript SDK, when loaded asynchronously, provides a similar mechanism: Facebook Javascript SDK在异步加载时提供了类似的机制:

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? 在DOM Facebook的SDK都完全初始化之前,延迟代码运行的最优雅方法是什么?

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: 可能在fbAsyncInit函数中设置一个标志,并在jQuery加载中检查它:

$(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). 我希望已经有一些全局可以检查Facebook是否已加载(我没有使用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();
        }
    }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM