Importing JavaScript files

In the JavaScript development world, there are multiple ways to load script files. The most common is to load them using the <script> tag in the index.html file. Some frameworks allow loading script files at any time, via JavaScript. Phaser provides different ways to load the scripts, each one with its purpose:

  • this.load.script(...) [docs]: It loads and executes the provided script file or files in random order. This can break your code if one script depends on another that is not loaded yet.

  • this.load.scripts(...) [docs]: It loads a list of script files and executes them in the specified order (see the section below).

  • this.load.scenePlugin(...) [docs]: It loads and executes the script files, but assumes they create new Phaser.Scenes.ScenePlugin instances.

  • this.load.sceneFile(...) [docs]: It loads and executes the script files, but assumes they create Phaser.Scene instances.

So the same Phaser framework can be used as a JavaScript packing/loading tool, and it has a few clear advantages:

  • You can load the scripts on demand when needed, such as when the game has many levels.

  • You can report loading progress of script files, just like you do with other assets.

  • Scripts can be added to an Asset Pack file using the Phaser Editor 2D toolset.

By the way, when you add an entry for a JavaScript file to an Asset Pack file, and that script is associated with a Scene Editor file (.scene), the Asset Pack Editor shows an inline preview of the scene, for easy identification.

Scene JavaScript files are displayed with a scene screenshot.

Execution order of the scripts

A missing class is a common error when you load scripts using the Asset Pack Editor. It happens when a class B in a script B.js extends a class A in the script A.js, but B.js is executed before A.js. The solution is to use the Scripts file type. With this method, you can set execution order of the files:

Select to add a Scripts file type. Select to add a Scripts file type.