Best way to go about using multiple Javascript files?

Viewed 116

So I'm intending to create a 'web arcade' in a sense, and I want different Javascript files to run when selecting a different game, what's the best way to go about doing this?

Is it possible to run a Javascript file on click of a certain button on the HTML page? I've tried using Modules but that seems a little complicated for my level at this moment, and was hoping for an easier alternative.

Thanks!

2 Answers

You are able to just include script tags with the src to your various files. A think to note is that you must pay attention to the order that you are loading them in at. Furthermore, you can just declare the variables regularly with const/let/var and use them regularly in files that load after it.

<!DOCTYPE html>
<html>
  <head>
    <script src="settings.js"></script>
    <script src="loop.js"></script>
  </head>
</html>
// settings.js
const worldData = {
  size: [230, 342]
};
// loop.js
console.log(worldData); // logs `{ size: [230, 342] }` because this file is loaded after `settings.js`

function draw() { /* omit */ }
// call `draw` in a loop somewhere with HTML5 Canvas or P5

However, I would strongly suggest using ES Modules. They make your code much more understandable like in the following project:

<!DOCTYPE html>
<html>
  <head>
    <script src="loop.js" type="module"></script> <!-- Note that we only need this entry file -->
  </head>
</html>
// settings.js
export const worldData = {
  size: [230, 342]
};
// loop.js
import { worldData } from "./settings.js" // automatically sends request and gets script exports

console.log(worldData); // logs `{ size: [230, 342] }` because we already imported it

function draw() { /* omit */ }
// call `draw` in a loop somewhere with HTML5 Canvas or P5

The ES Modules version is much better because if you had many files that accessed the worldData, then you could just do an import { worldData } from "/settings.js" instead of having to ensure that your files are loaded in the proper order.

You could fairly easily just separate your javascript into separate files and include them all in your HTML as a <script>.

Related