+ 1
How to use multiple JS files in the same html file | not working for me
I'm trying to use multiple js files in one page. My plan was to have a nav.js file which I can use for multiple pages, to operate the nav. Then another file which is only for a specific page. so in the code it becomes: <head> <scr.. src = "nav.js"> </scr...> <scr.. src = "games-page.js"> </scr...> </head> But it won't work. Only the first file works (in this case nav.js). If I flip it and put games-page.js first, nav.js won't work. I tried async and defer, but had no luck. any ideas? </head>
12 Answers
+ 1
A few alternative solutions
https://repl.it/@Charles_Comer/multiple-JS-files-1
https://repl.it/@Charles_Comer/multiple-JS-files-2
https://repl.it/@Charles_Comer/multiple-JS-files
https://javascript.info/modules --as a reference
+ 3
Ginfio
Problem maybe both files are not compatible with each other.
+ 3
Ginfio
Means maybe nav.js made with another version of jQuery and games-page.js made with another version of jQuery.
+ 2
Maninder $ingh just plain js:
like this..
https://code.sololearn.com/WA2iNaNA7O16/?ref=app
+ 2
Ginfio this is not a problem with your scripts your both scripts are calling when head tag call. This is a problem with alert tag when the first alert is called the second alert not don't get the time to run. Just add a delay after the first alert. Will work. You can also do something with second scripts like by console.log
Look at here.
https://stackoverflow.com/questions/50412050/alert-is-not-working-second-time-when-clicking-on-button
+ 1
Ginfio it should be worked because you call Js files as many as you want to call in the head tag. Btw what type of codes those both files has. Do these files are using jquery or something.
+ 1
Ginfio on which code editor you are running your code like VS code something. Do both files are present in the same folder.
+ 1
Maninder $ingh here is the code.
https://repl.it/@205135tmd/multiple-JS-files#script2.js
and the output:
https://multiple-js-files.205135tmd.repl.co/
0
@I Am Groot ! what does that mean?
0
You can use the javascript function to call the particular script.
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
And call this function where you want to apply the js file.
loadScript('nav.js');
Hope it helps.
0
@I Am Groot ! no. file are compatible. Just plain JS.
and @Shaili Shah, tried it multiple times, no luck.
0
See this:https://www.quora.com/Can-I-call-two-JavaScript-files-in-one-HTML-file
https://en.owl.institute/javascript-fundamentals/javascript-manipulating-html-with-ease/using-multiple-js-files
You can see the defer keyword in one of the js scripts.