Will the script load with the onload event when the async attribute is delayed?

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

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

Since it contains the async attribute, it loads asynchronously, and the browser parses the page without waiting for this script to load. After loading, this script will also be executed asynchronously so that the browser continues parsing the page.

This script, after loading, will perform some actions and insert another script dynamically through 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 run asynchronously, and again the browser can continue to work on other things, so if necessary, smooth the page or by running other scripts.

Now, I understand that this script, from the beginning to the end of its execution, will not block the browser in any way. It will load, add another script, and execute completely asynchronously. DOMContentLoaded event will not slow down at all.

Perhaps this could delay the firing of the onload ? It seems to me that this script will start when the page is almost analyzed. It will then request other scripts, and the onload may be delayed, waiting for this last script to complete its task.

Do I understand correctly?

EDIT

Added test for http://plnkr.co/edit/BCDPdgCjPeNUmLbf7wNR?p=preview and in Chrome it seems that it delays the onload event

+6
source share
1 answer

Yes, you think it delays the window.onload event.

Your first script, somescript.js adds a script child to the page before the page finishes loading (for example, before window.onload fired), and now the page must load and execute src of this newly added script element before it can fire the onload .

If you did not want it to delay the onload , you could make an AJAX request to get the contents of otherscript.js and just eval so that it otherscript.js in a global context (effectively the same as specifying it with a script tag, but without onload delays).

+4
source

Source: https://habr.com/ru/post/985009/


All Articles