mosceo
mosceo

Reputation: 1224

"async" attribute for the <script>

The documentation says about the async attribute: "Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously." I thought that even without this tag all external scripts are executed asynchronously. Was I wrong?

If I have declared several external scripts, will they be downloaded simultaneously or one by one? In which order they will be executed?

<script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js"></script>
<script type="text/javascript" src="js/3.js"></script>

Upvotes: 2

Views: 181

Answers (2)

Christoph
Christoph

Reputation: 51261

A script element needs to be resolved immediately. If it's an inline script everything is fine, but if it is an external resource, it needs to be downloaded first.

While downloading, it is blocking the page rendering and possibly other downloads. That's why one should put script blocks at the end of the body tag to block as few other processes as possible.

Whether your 3 scripts are downloaded in parallel or one after another depends on the browser. Modern browser do several http requests at the same time and thus have better page rendering times. However, independent from which of the scripts has finished loading first, the order of execution is always fixed - the scripts get executed in the order they appear in your html markup (in your example: 1.js -> 2.js -> 3.js). So a very small .js file which appears last in the source might be avaiable first, but has to wait with execution for all other sourcefiles to be downloaded and executed which appear before.

That's why they introduced async - which basically tells the browser: "The order of execution doesn't matter, just download it and execute it when it's finished donwloading and you have some spare time."

Upvotes: 1

Quentin
Quentin

Reputation: 944320

Yes. Scripts are, by default, blocking. HTML parsing will stop until the script has finished executing (noting that some function calls made by the script might be handled asynchronously and those won't block further rendering).

If this wasn't the case, then:

<script src="foo.js"></script>
<p>Hello

and

document.write("foo!");

might insert foo! into the HTML some time after Hello because it would take time for the script to download before being executed.

Upvotes: 4

Related Questions