Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Load" event on script with async and/or defer

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.

like image 375
Ale Morales Avatar asked Oct 22 '16 14:10

Ale Morales


1 Answers

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.








Edit: added important information originally from comment.

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.
like image 66
Danoram Avatar answered Oct 02 '22 16:10

Danoram