I lazyload multiple script files. I want to call allJsLoaded() method when all files are loaded in order. Since the script files load synchronously, is it enough to listen to onload event of last script tag? Or is there any better approach to achieve the same?
//Below are the script tags I create dynamically and add it to headtag
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="file3.js" onload="allJsLoaded()"></script>
2
Answers
If the script files are loaded synchronously (meaning one after the other, in order), then listening for the onload event of the last script tag should be sufficient to ensure that all scripts have loaded before calling
allJsLoaded()
.This approach assumes that the scripts are loaded without any errors and that they do not manipulate the loading order or execution flow. If there’s a possibility that any of these conditions might not be met, you should consider
additional error handling
.Keep in mind that in some cases, particularly if the scripts are loaded from different domains or have other complex dependencies, you might encounter issues with the
onload event due to cross-origin restrictions
. In such cases, you might need to use a more advanced script loading technique or a module loader likeRequireJS
.You also could use defer like this :
https://www.w3schools.com/tags/att_script_defer.asp
Also i’m not particularly fond of using a function on "onload".
If you want to be sure that everything is loaded, use an eventListener instead :
use this doc : https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
While i’m on the event listener you also have this event :
https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event