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
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
Just pass the variable:
or make it global
Try using the "defer" while importing the js file, like
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.