Why are JavaScript widgets (like the Tweet and Facebook buttons) dynamically add a script?

Both the Tweet and Facebook Like buttons see the widgets; you 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 JavaScript widget. Why is this done dynamically, instead of directly loading the widget (it's easier and cleaner):

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

The only reason I can think of is that it delays the loading of the script until the page loads, but this can be done just as easily by putting <script> just before closing </body> .

+4
source share
2 answers

Because people implementing this code cannot be competent enough to put the script in the right place. In addition, the script would ideally be versatile enough so that anyone using any system could easily implement it.

Some CMSs do not allow small-scale control over where scripts are added to the page. It is in the interest of social networks to provide code that more people can use with less confusion.

+1
source

When you add the same script, it loads asynchronously and will not block the rest of your HTML from loading. If it were the <script> tag added to the <head> , the rest of your HTML was not parsed until the script was finished loading, and this could jeopardize the user's work. However, you will get almost the same download result asynchronously if you add the <script> block immediately before </body> .

(I assume zzzzBov means "the right place.")

0
source

All Articles