I have seen facebook javascript api mentioning that loading the sdk asynchronously
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
what is the difference in loading a script using the script tag directly like the following
<script src='as.js'></script>
and the above shown code
The
<script>tag loads the javascript synchronous in a guaranteed order. The script will load before other things that follow it (other scripts or other elements of the page).The first option in your code example loads it asynchronously with no predictable order relative to the other things on your page.
Asynchronous loading has the advantage that nothing in the page
waitsfor the script to load and the page can render before the script finishes loading. Asynchronous loading has the disadvantage that you can only know when it’s loaded and available for use if you either monitor a load event for that script or if it calls you when it loads and runs or if you poll for some artifact that it makes available when it runs.Synchronous loading (using
<script>tags has the advantage that scripts load in a predictable order so you can load library scripts first and then scripts that use those libraries and know that they will be loaded in the desired order without any special coding. Synchronous loading of a script that occurs before all the body content can significantly slow down the rendering of the content that follows it because the script has to both load and execute before the rest of the page can be loaded and rendered.