Kristian
Kristian

Reputation: 21830

Embedding javascript snippets: tag injection vs a complete tag

on the facebook developer docs, i see:

<html>
    <head>
      <title>My Great Web page</title>
    </head>
    <body>

      <div id="fb-root"></div>
      <script>
        // Load the SDK Asynchronously
        (function(d){
           var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
           if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
           ref.parentNode.insertBefore(js, ref);
         }(document));
      </script>

      <div class="fb-like"></div>

    </body>
 </html>

Like google analytics, among many other things, this generates a script tag, and inserts it into the dom.

Why not just write <script type="text/javascript" src="someUrl.com/etc"></script> to begin with?

I assume its to prevent blocking behavior by loading / injecting after page load (aka async). is async the only reason??

Upvotes: 2

Views: 130

Answers (1)

Ibu
Ibu

Reputation: 43840

This form of loading the script adds it to the page asynchronously.

The attribute js.async = true; is not supported on older browsers so this is kindof a hack to make it work even on older browers.

How it works: it adds the script to the head or an already loaded part of the dom, to prevent the browser from download this script before moving on.

Upvotes: 3

Related Questions