如何等待另一个JS加载以继续操作? [英] How to wait for another JS to load to proceed operation?

查看:66
本文介绍了如何等待另一个JS加载以继续操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.我的一个JS脚本需要Facebook SDK和Twitter窗口小部件JS才能首先加载. Facebook创建FB对象,Twitter创建twttr对象.即使从<head>加载它们,它们也会在我的脚本触发后创建这些对象.

I have an issue. One of my JS scripts needs Facebook SDK and Twitter widgets JS to load first. Facebook creates FB object, Twitter creates twttr object. Both of them create these objects AFTER my script fires, even though they're loaded from <head>.

我认为解决方案是定期检查FB和twttr是否已定义,然后继续执行我的脚本.但是我不知道该怎么做.

I think solution is to periodically check if FB and twttr are defined, and then proceed with executing my script. But I have no idea how to do this.

我尝试创建循环

while (typeof FB === 'undefined' || typeof twttr === 'undefined' || typeof twttr.widgets === 'undefined') {
    // run timeout for 100 ms with noop inside
}

但这显然不起作用,因为它会保持高速触发超时并导致页面挂起.

But this clearly does not work as it keeps firing timeouts at a high speed and page hangs.

请帮助我,由于这个问题,我无法入睡.

Please help me, I can't sleep because of this issue.

推荐答案

如果以正常的同步方式加载脚本,则只需确保您的 <script>包含出现在文档<head>中的库脚本的之后.另一方面,如果这些脚本正在异步加载对象(似乎是这种情况),则创建如下所示的内容:

If the scripts are loaded in the normal, synchronous way, then just make sure that your <script> include appears after the library scripts in the document's <head>. If, on the other hand, those scripts are loading objects asynchronously (as seems to be the case), then create something like this:

function whenAvailable(name, callback) {
    var interval = 10; // ms
    window.setTimeout(function() {
        if (window[name]) {
            callback(window[name]);
        } else {
            whenAvailable(name, callback);
        }
    }, interval);
}

并像这样使用它:

whenAvailable("twttr", function(t) {
    // do something
});

在全局window对象上定义了twttr之前,将不执行在whenAvailable的第二个参数中给出的功能.您可以为FB做同样的事情.

The function given in the second argument to whenAvailable will not execute until twttr is defined on the global window object. You can do the same thing for FB.

重要说明::这些库可能还提供了一些内置方法,可以在加载后 执行代码.您应该在各自的文档中查找此类钩子.

Important note: Those libraries probably also provide some built-in way to execute code after they have loaded. You should look for such hooks in their respective documentation.

这篇关于如何等待另一个JS加载以继续操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆