Reputation: 111325
Instead of just including <script src="...">
tag on a page as usual, facebook recommends loading its SDK library in the following way:
<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 put the asynchronous version of the code is right after the opening
<body>
tag. This allows Facebook initialization to happen in parallel with the initialization on the rest of your page.
If it is that great then maybe I should always use this method in all my projects for any external javascript include? When it is appropriate to use this technique and what are the reasons against it?
Upvotes: 4
Views: 2972
Reputation: 12140
Asynchronously loading a script sounds good, but do you need to do it in an inline <script>
tag?
What about loading it while handling the onload
of the 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 Facebook's way ensures all script-enabled browsers process the script, but you can pretty much ensure those same browsers handle the script with a nice addEventListener/attachEvent abstraction function.
Upvotes: 0
Reputation: 21911
Every script-tag forces the browser to stop loading, until the script-block is fully loaded and executed. By dynamically adding the script-tag, the page could be fully loaded without blocking. For further info have a look at Loading Javascript without blocking and/or loading scripts without blocking
Upvotes: 3