I am having troubles accessing a function of a js file from another file.
I have created a new file named "test.js" in the same path as main.js file.
In test.js I have only a function:
function HelloWorld(){
console.log("hi user");
}
And now I want to call this function in the main.js. In the main.js I have the code where I append a script tag of the test.js.
var script = document.createElement('script');
script.type = 'module';
script.src = './test.js';
document.head.appendChild(script);
console.log("head=",head.document)
HelloWorld();
Here in the browser's console I can see that the script tag is added successfully there.
But when I want to call the test.js function HelloWorld(); it throws an expection saying "HelloWorld" is not defined
.
What am I missing here?
CodePudding user response:
You have two problems:
- The current script hasn't finished running so the other script can't have run so can't have created the function in time
- The other script is being loaded as a module, so the function it creates won't be in the global scope anyway
Use modules properly instead of trying to fake them using DOM and globals.
function HelloWorld(){
console.log("hi user");
}
export default HelloWorld;
and
import HelloWorld from './test.js';
HelloWorld();
CodePudding user response:
Try this one
const script = document.createElement("script");
script.src = "./script.js";
script.onload = () => {
HelloWorld();
};
script.onerror = () => {
console.log("Error occurred while loading script");
};
document.head.appendChild(script);