0

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?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jack
  • 21
  • 4
  • 2
    This seems fine but why declare functions in the anonymous function? You can declare those anywhere in the script, you just need to call those in `DOMContentLoaded`, `file` variable can be used as a parameter. – Harshit T Aug 24 '23 at 10:33

2 Answers2

1

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
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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.

vicky KG
  • 1
  • 1