Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I include one js file to another?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading