Should I always use the dynamic script tag loading method to include javascript files similar to Facebook?

Instead of just including the <script src="..."> on the page, as usual, facebook recommends loading your SDK library as follows:

 <div id="fb-root"></div> <script> (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> 

Saying that:

The best place to place the asynchronous version of the code is right after the opening of the <body> . This allows Facebook to initialize in parallel with the rest of your page.

If this is so cool, maybe I should always use this method in all my projects to include any external javascript? When is it advisable to use this technique and what are the reasons against it?

+4
source share
2 answers

Each script -tag causes the browser to stop loading until script-block is fully loaded and executed. By dynamically adding script -tag, the page can be fully loaded without blocking. For more information, see Downloading Javascript Without Blocking and / or Downloading Scripts Without Blocking

+3
source

Asynchronous script loading sounds good, but do you need to do this in the built-in <script> ?

How to load it when working from the onload page?

 function init() { (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.body.appendChild(e); }()); } window.addEventListener("load", init, false); 

Perhaps the Facebook method ensures that all script-blocked browsers process the script, but you can pretty much guarantee that the same browsers process the script with the nice abstraction function addEventListener / attachEvent.

0
source

All Articles