How to run multiple JS files? [solved]

I am working on a static site, and I want to split my index.js file into 2 smaller files: one for the actual script, and another for all the data. For me, only the index.js file is running. Right now my other file is supposed to just save all the data to a global variable, but it’s not running at all. Is there a way to run multiple JS files in a project? I have explored solutions such as browserify but I cannot figure out how to install them into a Glitch project.

Edit: I could save all the data in an .env file but I would rather leave the data public

Hey welcome to the forum! I just looked at your project. Based on my experience, you need to link the second JS file just like you did the first, in the head with defer. Remember that JS is sequential so they will run in order. So if you need one to run first, just list it first.

1 Like

Thank you so much; I completely forgot about the fact that all the scripts are in the head

No prob, and FYI there’s an option to do a Gallery post when/if you want to share your finished project!

Just a note but modern best practices suggest that you should load your scripts just before the closing tag. And that (when possible) you should reduce the number of files.

I’ve heard and read from multiple sources that putting the script above the closing body tag is an older approach, while putting it in the head is standard now, with defer and/or async. Sometimes I will even use an event listener in the script in the head with DOMContentLoaded, while other times defer does the trick.

That said, I’ve also run into unexpected behavior in different use cases where one approach worked and the other didn’t. I think for a small app either way is fine and would only be a difference of nanoseconds, probably, if any.

Hey sorry for late response, but you are not required to use the script files, in the .html file you can use a tag by the code you put it to. I would recommend using

, and
to separate the scripts.

Hope this helps.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.