When embedding scripts like:
<script src="..." async defer></script>
Is there a way to know when they're finished loading?
Usually when the window.load
event is called, one would expect all scripts to be ready as well. But I don't know if that still holds when you load them with async
or defer
. I've read some docs online but couldn't find anything conclusive on this issue.
Answer:
You could take advantage of the onload
event attribute in order to perform some kind of callback once your script is loaded.
Example:
In the example html script element below when the script (jquery library from google api) finishes loading asynchronously, an alert will pop up saying 'resource loaded'.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" async defer onload="alert('resource loaded');">
Note: The src script will load very fast because it is hosted by google so the pop up will most likely appear as soon as the page/DOM has loaded.
window.onload
waits for everything to load before firing whereas document.onload
fires when the Document Object Model (DOM) is ready.
So if you've got async scripts document.onload
will execute first while window.onload
will wait for those asynchronous scripts to finish loading.
To summarize:
window.onload
will take async scripts into account.document.onload
will not take async scripts into account. 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