spirytus
spirytus

Reputation: 10946

Are there any benefits to moving async scripts to the bottom of the page?

I have a page with a script tag in HEAD section:

<script src="somescript.js" type="text/javascript" async></script>

As it contains async attribute it loads asynchronously and browser parses the page without waiting for this script to be downloaded. Once downloaded, this script will execute, also asynchronously so browser can continue on parsing the page.

This script, once downloaded will perform some actions and inserts yet another script dynamically via something similar to this:

var a = document.createElement('script');
    a.type = 'text/javascript';
    a.src = 'http://domain/otherscript.js';

    var elem_body = document.getElementsByTagName('body')[0]; 
    elem_body.appendChild(a);

This new dynamically inserted script will also be executed asynchronously and again browser can continue on to other things, so parsing the page or executing other scripts as needed.

Now, my understanding is that this script, from beginning to the end of its execution will not block browser in any way. It will load, insert another script and execute completely asynchronously. `DOMContentLoaded event will not be slow down at all.

It will however slow down window's onload event as until this script is executed completely this event will not fire.

My question is would there be any benefit to moving this to the bottom of the page? It seems that as everything happens asynchronously it would not make any difference apart from the <script ..> tag call itself. If anything it could actually slow down onload event as this will be executed only when everything is done including asynchronous scripts execution. As this script would start when the page is almost parsed onload event would be possibly delayed further waiting for this last script to do its thing.

Is my understanding correct?

Upvotes: 3

Views: 747

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11320

Only if the browser does not support async. If it does not, it will block execution wherever it finds the <script> tag. I would put it at the bottom just in case.

Upvotes: 4

Related Questions