skip to Main Content

I have a html document and after the document is loaded I want to execute some JS code that is in another file.

So far I tried it with adding an EventListener at the beginning of the JS file with event "DOMContentLoaded".

document.addEventListener("DOMContentLoaded", function () {
  let file = document.getElementById("test");
  function test1(){
    someCode...;
    using file variable;
  }
  function test2(){
    someCode...;
    using file variable;
  }
});

But now all the other functions and the code is in this anonymous function. Is there another way to achieve that the JS Code only get executed after the content of the html document is loaded? Or is it ok/conventional that all the code is in this anonymous function?

3

Answers


  1. You could use JQuery method $.getScript( url, [callback] ) to load the script form another file with location passed as url parameter and then use the script in the callback function,

    You can refer to this very detailed answer https://stackoverflow.com/a/950146/13082747

    Login or Signup to reply.
  2. Just pass the variable:

    function test1(file) {
      someCode...;
      using file variable;
    }
    
    function test2(file) {
      someCode...;
      using file variable;
    }
    
    document.addEventListener("DOMContentLoaded", function() {
      let file = document.getElementById("test");
      test1(file);
      test2(file);
    });
    

    or make it global

    let file; // now accessible to the whole page
    function test1() {
      someCode...;
      using file variable;
    }
    
    function test2() {
      someCode...;
      using file variable;
    }
    
    document.addEventListener("DOMContentLoaded", function() {
      file = document.getElementById("test");
      // here you can assign the events that uses test1 and test2
    });
    
    Login or Signup to reply.
  3. Try using the "defer" while importing the js file, like

    <HTML>
        <body>
            <script src="externalFile.js" defer></script>
        </body>
    </html>
    

    defer loads the file asynchronously with the HTML document and executes it after the HTML document is parsed fully. I’m not sure if it works or not, but give it a try.

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