2

what is the difference between Html5 async attribute vs js async property.

<script src="http://www.google-analytics.com/ga.js" async>

and

(function() {
    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; 
    ga.async = true;
    ga.src = 'http://www.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(ga, s);
})();

are they interchangeable

2
  • (function() {...}); is on <head>...</head> or in on js file? Commented Jan 22, 2014 at 11:55
  • I believe that within the head tag the effect is the same. Personally I prefer <script> with <head>, perhaps the reason google-Analitics is only detect https or http, like @SalmanA said). Commented Jan 23, 2014 at 16:13

2 Answers 2

3

No, they are not interchangeable.

Script tag with async attribute executes at the first opportunity after it is downloaded and before window.onload event. So you dont know when that script executes. On the other hand, script loaded within a javascript file can execute whenever you want (after or before window.onload event).

Some links: http://davidwalsh.name/html5-async, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script.

Edit: ga.async = true; as said in Salman A. answer (https://stackoverflow.com/a/14666847/2044286) is omitted by the parser.

Sign up to request clarification or add additional context in comments.

2 Comments

So what happens if you set s.async = false?
Nothing. It has no effect (for small files, at least).
0

The JavaScript is creating the HTML element you are talking about. In JavaScript, the property itself has no meaning, in this case its just a property with the value true.

When the browser reads the HTML, the value gets a meaning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.