Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  59] [ 2]  / answers: 1 / hits: 35732  / 8 Years ago, sat, october 22, 2016, 12:00:00

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.


More From » html

 Answers
107

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.


[#60316] Wednesday, October 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maximusbradforde

Total Points: 594
Total Questions: 106
Total Answers: 82

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;