简体   繁体   中英

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?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM