如何确保此javascript的连续顺序?

时间:2013-01-01 10:26:29

标签: javascript asynchronous

要开始我的页面,我会检查Facebook以获取用户的登录状态。然后,我在窗口对象中创建一个名称空间,以便在其他javascript文件中使用。在我加载任何其他javascript之前,我需要创建这个命名空间,否则当我尝试访问它时它将是未定义的。有时它首先完成,有时则不完成。我怎样才能确保每次都能正确发生?

.
.
.
        FB.getLoginStatus(function(response) {
          // store data on the user inside of a namespace 
          // inside of the window object so it can be accessed
          // from anywhere. Use this like '$_SESSION'
          console.log('doing it');
          window.easyUserData = {
            fbRespose: response,
            site: <?php echo '"'.$site.'"'; ?>
          };
        })
      };

      (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/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
      }(document))
    </script>
    <!-- Load the script "js/main.js" as our entry point for require -->
    <script data-main="js/main" src="lib/Require/require.js"></script>

具体来说,我需要:

<script data-main="js/main" src="lib/Require/require.js"></script>

直到facebook功能完成才会发生

2 个答案:

答案 0 :(得分:1)

将依赖于命名空间的代码移动到 Facebook回调中。如果是<script data-main="js/main" src="lib/Require/require.js"></script>,请动态创建script元素:

  // ...

  FB.getLoginStatus(function(response) {
    // store data on the user inside of a namespace 
    // inside of the window object so it can be accessed
    // from anywhere. Use this like '$_SESSION'
    console.log('doing it');
    window.easyUserData = {
      fbRespose: response,
      site: <?php echo '"'.$site.'"'; ?>
    };

    // Create the script element when ready
    var script = document.createElement('script');
    script.setAttribute("data-main", "js/main");
    script.src = "lib/Require/require.js";
    document.getElementsByTagName('script')[0].parentNode.appendChild(script);
    // Or instead of `document.getElementsByTagName('script')[0].parentNode`
    // you can use `document.documentElement` or `document.getElementsByTagName('head')[0]
    // or a few others
  })
};

答案 1 :(得分:0)

可以将它全部移动到一个地方,正如TJ建议的那样。 您可以在尝试运行自己的代码之前检查您的变量是否已创建:

// First this:
FB.getLoginStatus(function(response) {
    window.easyUserData = {
        fbRespose: response,
        site: <?php echo '"'.$site.'"'; ?>
    };
});

// Later in the code:
(function () {
    var isFBLoaded = function () {
        // If FB has loaded - run our code
        if (window.easyUserData) {
            myOtherFBStuff();
        }
        // If not - check again in 500 ms
        else {
            setTimeout(isFBLoaded, 500);
        }
    };

    var myOtherFBStuff = function () {
        // do stuff here
    };

    isFBLoaded();
})();