skip to Main Content

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


  1. 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 like RequireJS.

    Login or Signup to reply.
  2. You also could use defer like this :
    https://www.w3schools.com/tags/att_script_defer.asp

    <script type="text/javascript" src="file3.js" onload="allJsLoaded()" defer />
    

    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 :

    document.addEventListener("load", function(){
        //....
    });
    

    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 :

    document.addEventListener("DOMContentLoaded", function(){
        //....
    });
    

    https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search