0

我正在使用 facebook SDK for Javascript,有人可以解释异步加载 SDK 是什么意思,这段代码如何表示它是异步加载的,以及这将如何影响我的应用程序。

// 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";
       ref.parentNode.insertBefore(js, ref);
      }(document));
4

1 回答 1

2

min2bro, there are generally speaking two ways an script/SDK can load:

Synchronously. This is what is generally the default when you include stuff. It's assumed that when you ask for something, the browser MUST wait for it to be included before fetching other stuff. In other words, it will only do 1 thing at a time. This is nice and simple. It's "linear" and you can easily trace what happens.

Pros: Simplicity. Easy to understand, easier to work with. Causes less headaches for the developer.

Cons: Speed and user experience. If you have 5 social like/share/pin/whatever buttons on the same page (from different services), it will significantly slow down your page, in the sense that the user may not be able to scroll down and see the rest of the page, because they are waiting for the like buttons to appear.

Asynchronously. For scripts, it will only happen if you manually specify it, as you are trying to here. It means that you are saying "It's ok for the user to see the entire page and begin scrolling before the Facebook SDK is available". The "Facebook SDK" refers to any functionality that relates to Facebook, like "like" buttons, Facebook connect, etc.

Pros: Speed and user experience. If you have a lot of scripts on your page, your user can still read the article/see the page and enjoy the content.

Cons: Harder to work with. Depending on what site you got, you may need to restructure your code so it waits for the Facebook SDK to become available. You can't just include a random script after the snippet you pasted and expect it to work. You'll have to wrap your functionality in an event handler, specifically window.fbAsyncInit = function () { ... }

TL;DR: Async means you may need to make changes to your own code, if it relies on the Facebook SDK. Like buttons, etc. may take a bit longer appear. Async also means a better user experience.

于 2014-03-01T20:43:15.790 回答