Mohamed Said
Mohamed Said

Reputation: 4613

Using window.fbAsyncInit doesn't work on the first load of a page

<script>
        (function(d, debug){
            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/ar_AR/all.js#xfbml=1&appId=356233997758493";
            ref.parentNode.insertBefore(js, ref);
        }(document, /*debug*/ false));  
</script>

That's how I init facebook sdk, the problem is when I load the page for the first time any code inside window.fbAsyncInit doesn't load, but when I refresh the page it works fine.

Do you have any idea what the problem may be?

Upvotes: 3

Views: 2408

Answers (2)

adamdport
adamdport

Reputation: 12633

I resolved this by moving my Facebook's SDK snippet to the very bottom of my index file, just before the closing </body> tag.

  ...
  <script>
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
  </script>
</body>

Upvotes: 1

userC
userC

Reputation: 16

You can work around this by using window.onload to wrap any functions you want performed on page load. Might not be pretty, but it works.

<script>
  //Executes on page load
  window.onload = function(){
    window.fbAsyncInit = function(){
        //Init stuff
    };
    FB.getLoginStatus(function(response) {
        //...
    };
  };

  // Load the SDK asynchronously
  (function(d){
    //stuff
  }(document));
</script>

Upvotes: 0

Related Questions