“Load” event on script with async and/or defer

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)