首页 > 解决方案 > Javascript. How to stop scripts from executing until all of them have loaded

问题描述

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?

标签: javascriptbrowser

解决方案


编写模块并使用像 Parcel 或 Webpack 这样的打包工具。

如果您引用另一个文件中的函数,请编写正确的导入:

import { myFunc } from ‘./otherModule‘

然后在您的 html 中,只需包含您的 main.js 或入口点脚本。


推荐阅读