简体   繁体   English

即使我刚刚使用它,FB仍未定义

[英]FB is undefined even though I just used it

I am trying to add a Facebook Like button to a widget that I am creating. 我正在尝试将Facebook Like按钮添加到我正在创建的小部件中。 The code that I use to add the Facebook like button to my page is as follows: 我用来将Facebook喜欢按钮添加到我的页面的代码如下:

widget.html widget.html

<body>
<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId  : '263071593731910',
            status : false, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML
        });
    };
    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
</script>
<div id="fb-button"></div>
<script type="text/javascript" src="widget.js"></script>

widget.js widget.js

$(function(){
var fb = $(document.createElement("fb:like"));
fb.attr({
    href: data.facebook,
    send: false,
    layout: 'button_count',
    width: 70,
    'show_faces': false
});
$("#fb-button").empty().append(fb);
FB.XFBML.parse($("#fb-button").get(0));
FB.Event.subscribe('edge.create',changeView);
});

*The changeView function does exist as well in the JavaScript. *在JavaScript中也存在changeView函数。

When I run the code, I get an error: Uncaught ReferenceError: FB is not defined even though the button is created. 当我运行代码时,我收到一个错误: Uncaught ReferenceError: FB is not defined即使创建了按钮,也Uncaught ReferenceError: FB is not defined The error is pointing to the line containing FB.XFBML.parse code. 该错误指向包含FB.XFBML.parse代码的行。 Is there something I need to do differently in my JavaScript? 我的JavaScript需要做些什么吗?

I had this problem and solved it similarly to the solution that Amry provided so I'm posting it here in case someone else needs to use it. 我遇到了这个问题并且解决了它与Amry提供的解决方案类似,所以我在这里发布它以防其他人需要使用它。

I made the initial assumption that the FB initialization call made in the fbAsyncInit method would initialize immediately, so I too coded my use of the FB object in a $(document).ready() method. 我初步假设在fbAsyncInit方法中进行的FB初始化调用会立即初始化,所以我也在$(document).ready()方法中编写了我对FB对象的使用。 That is not the case. 事实并非如此。 fbAsyncInit takes quite some time after the page loads to finish initializing. 页面加载完成初始化后,fbAsyncInit需要相当长的时间。 Here is my solution, when using jQuery on my site: 这是我的解决方案,在我的网站上使用jQuery时:

<script type="text/javascript">

  window.fbAsyncInit = function() {

    FB.init({
      appId      : 'your_app_id', // App ID
      channelUrl : 'your channel',
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });
    jQuery(document).trigger('FBSDKLoaded'); //This is the most important line to solving the issue
  };

  // Load the SDK Asynchronously
  (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#xfbml=1&appId=269187653191150";
     ref.parentNode.insertBefore(js, ref);
   }(document));

</script>

The last task is to simply switch your $(document).ready() code to a bind for your event. 最后一项任务是简单地将$(document).ready()代码切换为事件的绑定。 This goes where ever you are using the FB object. 这就是你使用FB对象的地方。

(function($) {
    $(document).bind('FBSDKLoaded', function() {
        //Code using the FB object goes here.
    });

})(jQuery);

One thing I should also mention: Firefox is a lot more tolerant of this than Webkit browsers like Chrome. 有一件事我还应该提一下:Firefox比Chrome等Webkit浏览器更容忍。 I couldn't figure out why NONE of my jQuery was working properly in Chrome... well, this was why. 我无法弄清楚为什么我的jQuery没有在Chrome中正常工作......好吧,这就是原因。

I hope this helps someone. 我希望这可以帮助别人。

The whole point of that big script block starting with window.fbAsyncInit is that the Facebook SDK gets loaded asynchronously . window.fbAsyncInit开始的那个大脚本块的重点是Facebook SDK被异步加载。

Even though you've got your calls against FB inside a jQuery document ready callback, that isn't sufficient to ensure the SDK is loaded when that code is executed. 即使您已经在jQuery文档就绪回调中对FB进行了调用,但这还不足以确保在执行该代码时加载SDK。

Fortunately, window.fbAsyncInit exists for exactly that purpose: it won't be run until the SDK has loaded. 幸运的是, window.fbAsyncInit 正是出于这个目的:在SDK加载之前它不会运行。

From Facebook's docs : 来自Facebook的文档

The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. 分配给window.fbAsyncInit在加载SDK后立即运行。 Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. 加载SDK后要运行的任何代码都应放在此函数中,并在调用FB.init之后。 For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested. 例如,您可以在此处测试用户的登录状态或订阅您的应用程序感兴趣的任何Facebook事件。

FB was not yet defined at that point of time. FB还没有定义在那个时间点。 You haven't used it yet, you had simply typed it earlier up. 你还没有使用它,你只需要早点输入它。 The FB.XFMBL.parse line will execute when the document is ready. 文档准备好后,将执行FB.XFMBL.parse行。 Same goes to the //connect.facebook.net/en_US/all.js line. 同样适用于//connect.facebook.net/en_US/all.js行。 So it's not really reliable which code will execute first if it is executed from the same event. 因此,如果从同一事件执行代码将首先执行哪个代码并不可靠。

What you can do is somehow have the code you want be executed from window.fbAsyncInit . 你可以做的是以某种方式从window.fbAsyncInit你想要执行的代码。 From that point onwards, you can be sure that FB is ready to be used. 从那时起,您可以确定FB已准备好使用。

One way you can do if you don't want to mix the code you have in widget.js is by using jQuery's custom event. 如果您不想混合widget.js中的代码,可以使用jQuery的自定义事件。 So instead of having $(function() { ... }); 所以不要使用$(function() { ... }); , you will have something along this line: ,你会有这样的东西:

$(window).bind('fbAsyncInit', function() {
  // Your code here
});

Then you will have window.fbAsyncInit call $(window).triggerHandler('fbAsyncInit') just after the FB.init() line. 然后你将在FB.init()行之后调用window.fbAsyncInit调用$(window).triggerHandler('fbAsyncInit')

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

相关问题 即使我加载了 js,方法也未定义 - Method undefined even though I loaded the js .map()未定义,即使我传递了数组 - .map() undefined even though I pass an array 未定义 Function 即使我在 Javascript 中定义了它 - Undefined Function Even though I defined it in Javascript 属性被标记为未定义,即使它在同一行上被完美使用? - property marked as undefined even though it is being used on the same line flawlessly? 角度控制器数组为空,即使我刚刚定义了它 - angular controller array empty even though i just defined it Javascript“变量声明但从未使用过”......即使我正在使用它? - Javascript “variable declared but never used”… even though I'm using it? TypeError:即使我创建了此函数,undefined不是一个函数 - TypeError: undefined is not a function even though i created this function 即使我声明了会话,Express-session也会返回“ undefined” - Express-session returns 'undefined', even though I declared the session 在控制台中获取未定义的错误通知,即使我正在检查未定义 - Getting undefined error notice in console even though I'm checking for undefined “无法读取未定义的属性‘映射’”,即使我明确告诉它如果数组未定义则不要运行 function - 'Cannot read property 'map' of undefined' even though I explicitly told it not to run the function if array is undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM