4

Both the Tweet Button and Facebook Like widgets tell you to add something like this to your HTML:

<script>
!function(d,s,id){
    var js,fjs=d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)){
        js=d.createElement(s);
        js.id=id;
        js.src="https://platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js,fjs);
    }
}(document,"script","twitter-wjs");
</script>

which dynamically adds a <script> element to the DOM which then loads the actual widget JavaScript. Why is this done dynamically instead of directly loading the widget like this (which is simpler and cleaner):

<script src="https://platform.twitter.com/widgets.js"></script>

The only reason I can think of is that it defers the script load until the page has loaded, but this can just as easily be accomplished by placing the <script> just before the </body> close.

mgorven
  • 328
  • 1
  • 10
  • 1
    This is a good question, but it really reminds me of [this question](http://stackoverflow.com/questions/14666658/document-createelementscript-vs-script-src/). – MikeSmithDev Feb 07 '13 at 03:21
  • @MikeSmithDev Yup, same thing. I did search SO before posting but didn't find that. – mgorven Feb 07 '13 at 03:23

2 Answers2

1

Because the people implementing this code can't be guaranteed to be competent enough to place the script in the right place. Additionally, the script would ideally be universal enough that anyone using any system could easily implement it.

Some CMSs don't allow fine-grained control of where scripts are added to a page. It's in the best interest of social networks to provide code that more people can use with less confusion.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

When you add a script like that, it's loaded asynchronously, and won't block the rest of your HTML from loading. If it were just a <script> tag added to the <head>, the rest of your HTML wouldn't be parsed until the script finished loading, and that could compromise user experience. However, you'd get virtually the same result of loading asynchronously if you added the <script> block just before </body>.

(I guess that's what zzzzBov means by "the right place".)

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • What I meant by "the right place" was that the script typically needs to come after some element or collection of elements with particular IDs or classes. – zzzzBov Feb 07 '13 at 03:43
  • I was assuming all the html needed by those scripts were created by the scripts themselves. I just checked, and it's not true (twitter requires you add an anchor too, and facebook wants a div). – bfavaretto Feb 07 '13 at 03:48