12

In this post, asynchronous .js file loading syntax, someone said, "If the async attribute is present, then the script will be executed asynchronously, as soon as it is available."

(function() {
  var d=document,
  h=d.getElementsByTagName('head')[0],
  s=d.createElement('script');
  s.type='text/javascript';
  s.async=true;
  s.src='/js/myfile.js';
  h.appendChild(s);
}()); /* note ending parenthesis and curly brace */

My question is, what does "the script will be executed asynchronously" mean? Will this script be executed in a different thread from other javascripts in the page? If yes, should we worry about synchronization issue in the two threads?

Thanks.

Community
  • 1
  • 1
Kai
  • 3,775
  • 10
  • 39
  • 54
  • This script is executed as soon as it is parsed, so I'm not sure there's any difference with just using the ` – djjeck Apr 19 '13 at 23:44
  • 1
    I believe the script should be added by `var fs = document.getElementByTagName('script')[0];fs.parentNode.insertBefore(s, fs);`. This way you're sure the script is not going to be parsed before completing the first parsing pass on the document. – djjeck Apr 20 '13 at 00:07

4 Answers4

23

Usually, when you add an external script to an HTML document, the script will need to be downloaded and executed before anything else can be done on the page. In other words, the script blocks. This can take a lot of time if there are several scripts to download.

But when you load a script asynchronously, it doesn't block. The rest of the page can be loaded and other scripts can be executed while the async script is downloading. This makes pages load faster, but this also means that you can't be sure when the async script will be executed. So you can't just start using functions and objects from the async script. You have to wait and check for the async script to load.

Example:

script1.js

var foo = "bar";

script2.js

alert(foo);

doc1.html

<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>

Result: "bar"

doc2.html

<script type="text/javascript" src="script1.js" async="true"></script>
<script type="text/javascript" src="script2.js"></script>

Result: "bar" or undefined, depending on whether or not script1.js has loaded yet.

No threads to worry about, though. One script executes after the other, but never both at the same time. It's just the order of execution that becomes unpredictable.

kijin
  • 8,702
  • 2
  • 26
  • 32
  • 7
    You can use `defer` keyword instead of `async` to ensure order is maintained as long as your scripts don't modify the DOM – stephenmurdoch Nov 23 '12 at 13:21
5

It will not be executed on different thread. You do not have to worry about thread synchronization in this case.

At some point later, after your current call stack unwinds, the download of myfile.js will complete. The browser and js framework will execute your script at some point after that.

Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294
selbie
  • 100,020
  • 15
  • 103
  • 173
2

Downloaded asynchronously, not executed asynchronously. Also, it's not necessarily executed when the download finishes.

goat
  • 31,486
  • 7
  • 73
  • 96
  • 4
    Could you expand on that more? Why it would it execute or not execute when it finishes? Do you mean it would be delayed? – Jeff LaFay May 25 '12 at 15:34
1
  (function(doc, script) {
    var js, 
        fjs = doc.getElementsByTagName(script)[0],
        add = function(url, id) {
            if (doc.getElementById(id)) {return;}
            js = doc.createElement(script);
            js.src = url;
            id && (js.id = id);
            fjs.parentNode.insertBefore(js, fjs);
        };

    // Google Analytics
    add(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
    // Google+ button
    add('https://apis.google.com/js/plusone.js');
    // Facebook SDK
    add('//connect.facebook.net/en_US/all.js', 'facebook-jssdk');
    // Twitter SDK
    add('//platform.twitter.com/widgets.js', 'twitter-wjs');
}(document, 'script'));

source: https://css-tricks.com/thinking-async/

Abed Yaseen
  • 522
  • 4
  • 12