Ilya Manyahin
Ilya Manyahin

Reputation: 238

Why Facebook ask me to put JS code instead of script tag?

If I want to add Like button to my page I should insert next code into my html code after the opening body tag.

<div id="fb-root"></div>
<script>(function(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/ru_RU/sdk.js#xfbml=1&version=v2.5&appId=12345";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Why I can not simple use script tag instead?

<script async src='//connect.facebook.net/ru_RU/sdk.js#xfbml=1&version=v2.5&appId=12345"'>

What benefits to use the facebook instructions?

Upvotes: 3

Views: 473

Answers (2)

Jerome WAGNER
Jerome WAGNER

Reputation: 22442

There can be several reasons :

  • IE 8 & IE9 do not support the script.async attribute as per http://caniuse.com/#feat=script-async
  • the facebook snippet does not load the script if there is already a facebook-jssdk element on the page (could have been loaded by another snippet)
  • your solution does not prepare a <div id="fb-root"></div>

Upvotes: 4

charrondev
charrondev

Reputation: 1149

The reason facebook recommends this (as do Google with their analytics, and many other companies) is to reduce the number of http requests in your page (by 1). Less requests generally means a faster website (things are a little different with http2). This is the same reason why it is recommended to concatenate your scripts, and css files.

You can read more about http requests here or other places online.

Edit: I guess I must have misread the question. Doing this does not incur another http request. The other answer is more accurate.

Upvotes: 1

Related Questions