I have the following html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="../script.js" language="JavaScript"></script>
.....
which I cannot change because of some objective reasons (so it’s not possible to change script type to "module" like I saw in other answers). I also have ../init.js file with a single function:
function init()
{
...
}
And now, I want access to the init function from ../script.js. So how can I do that and is this possible at all?
That’s what I’ve tried inside ../script.js file:
let script = document.createElement('script');
script.src = "../init.js";
document.head.appendChild(script);
window.onload = init;
But that wouldn’t work, because the browsers say that init is undefined
UPD.:
The problem is that now the init function is located directly inside ../script.js, but we want to move it into a separate file so that other scripts could use it as well and not produce duplicates
>Solution :
You can add an onload listener to the script you’re appending. When that fires, you know your init() function is defined.
let script = document.createElement('script');
script.src = "../init.js";
// Add an event listener for the 'load' event
script.onload = function() {
console.log("Script loaded and ready");
// You can now use init() as you'd like
};
document.head.appendChild(script);