0

I am trying to create small browser-game and have a lot of scripts sorted into different js files. Some of them reference other, each other and so on, therefore loading them in sequence so that first doesn't try and use function from second is not possible. Therefore I have a common problem:

One script tries to run function from other, that does not exist yet and creates an error, stoping script.

visual example of problem in console

Also often I recieve that error:

Uncaught ReferenceError: can't access lexical declaration 'something_something' before initialization

I tried to find solutions, but they don't seem to fit into my purpose:

  1. "<script defer/async>" will still try to do the same, but with their own timing, which will still cause the problem.

  2. window.addEventListener('load', function()) -- it is good solution, but not to my problem(i think), as it will still create some sequence of loading with errors.

  3. I can try and catch errors, but it will create a lot of additional not-efficient work and will probably need to reload scripts, so I am honestly not sure of how it will work.

  4. Modules can be used, probably? Not exactly sure as modules need to reference each other.

Basically all I need to do is to create something similar to a loading screen that a lot of programms have, so that nothing runs until everything loads. Or is it not how it works? I am pretty much a newbie in the programming.

Is there a way to do this? Or maybe there are some workarounds?

  • https://stackoverflow.com/questions/11258068/is-it-possible-to-wait-until-all-javascript-files-are-loaded-before-executing-ja – AL.Sharie Feb 28 '21 at 15:43

1 Answers1

0

Write modules and use a bundler like Parcel or Webpack.

If you reference a function in another file, write proper imports:

import { myFunc } from ‘./otherModule‘

Then in your html, just include your main.js or entrypoint script.

adroste
  • 758
  • 1
  • 7
  • 17