Async script loading is what i'm learning now. I have a question about async
attr in script tag - <script async src="...">
.
here is some info, http://www.w3schools.com/tags/att_script_async.asp and my question is about this - When present, it specifies that the script will be executed asynchronously as soon as it is available. line.
Question: If i have 2 scripts:
<script async src="url1.js"><script> // 200kb
<script async src="url2.js"><script> // 2kb
and the second script
must be executed AFTER first (it uses some Objects
or functions
from it) - will it be so after page load? will first script execute first after loading, and then - the second, or not?
From bold string above - I understand it so, that than faster the script
was loaded - the faster it will be executed, and in our example we will have errors, while first script
wasn't loaded and executed yet, but second is already trying to get it. (and when we can use async
script loading? only when our scripts are not independent of each other?)
p.s. is lazy loading script
the only way to get the correct script execution order in this case - to prevent errors?
Without the async
attribute, the browser will stop processing the page and first download the referenced script; once the script is downloaded and executed it will continue processing the next tag on the page. This has two consequences:
If you set the async
attribute, the browser will continue loading the page without stopping to process the script
tag, and will load the script sometime later. When exactly the script is loaded is undefined and you cannot depend on any particular order of execution. If you have dependencies between two scripts, you cannot load them async
hronously, because then it's down to pure luck whether one will load before the other.
As such, async
loading is only useful for scripts which have no other dependencies. Or: you hook your scripts to the window.onload
event and avoid making any cross references before then; the event will be fired after all scripts have loaded, including async
scripts.
If url2.js depends on url1.js you cannot use async loading for script files you must use synchronous (eager loading) to ensure that url1.js is loaded and executed before url2.js.
Using async two cases can occur:
Using non-async loading only one case can occur, which is url1.js loading and executing before url2.js loads and executes which is what you need if they depend on each other.
In async loading you can't control when they are executed, they execute as soon as they are loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With