0

要开始我的页面,我会检查 facebook 以获取用户的登录状态。然后我在 window 对象中创建一个命名空间以用于其他 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 功能完成之前不会发生

4

2 回答 2

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
  })
};
于 2013-01-01T10:28:23.007 回答
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();
})();
于 2013-01-01T10:40:02.387 回答