Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will script loaded with async attribute delay onload event?

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.

Hoever, will this possibly delay firing of onload event? It seems to me that as this script would start when the page is almost parsed. Then it would request other scripts and onload event would be possibly delayed further waiting for this last script to do its thing.

Is my understanding correct?

EDIT

Added test at http://plnkr.co/edit/BCDPdgCjPeNUmLbf7wNR?p=preview and in Chrome it seems that it does delay onload event

like image 229
spirytus Avatar asked Apr 12 '15 07:04

spirytus


1 Answers

Yes, as you suggest, it will delay the window.onload event.

Your first script, somescript.js adds a child script element to the page, before the page has finished loading (e.g. before window.onload has fired), and the page now has to download and execute the src of that newly appended script element before it can fire an onload event.

If you didn't want it to delay the onload event, you could make an AJAX request to get the contents of otherscript.js and simply eval it so it executes in the global context (effectively the same as specifying it via a script tag, but without delaying the onload event).

like image 167
Adam Avatar answered Dec 10 '22 08:12

Adam