Categories
Vue Answers

How to wait for the Facebook SDK to load in a Vue.js component?

Spread the love

Sometimes, we want to wait for the Facebook SDK to load in a Vue.js component.

In this article, we’ll look at how to wait for the Facebook SDK to load in a Vue.js component.

How to wait for the Facebook SDK to load in a Vue.js component?

To wait for the Facebook SDK to load in a Vue.js component, we can put the Facebook SDK initialization code in the created hook.

For instance, we write

<template>
  <div id="app">
    <div v-html="innerHtml"></div>
  </div>
</template>

<script>
//...
export default {
  //...
  created() {
    window.fbAsyncInit = () => {
      FB.init({
        appId: "1111111111",
        xfbml: true,
        version: "v2.7",
      });
      FB.getLoginStatus((response) => {
        console.log(response);
      });
    };

    ((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>

to add the Facebook SDK initalization code into the created hook.

And then we get the response from the getLoginStatus callback when the Facebook SDK is loaded.

Conclusion

To wait for the Facebook SDK to load in a Vue.js component, we can put the Facebook SDK initialization code in the created hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *