Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

asynchronous javascript loading/executing

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...