I have a solution in my project that has worked very well, however the downside is that its implementation is very tied into the other existing infrastructure I have written for the project, so it's not like I can just simply send you a couple files so you can be on your way.
I can however explain a bit how I accomplished it, and if more info is required, hit me up on the ImpactJS IRC chat room (same name) and I can provide more specific info.
Basically I needed a system where I would only load the current level that I need to play, and once I move onto another level, I would need to remove/clear out any and all garbage created by that level, and load up the next one.
To accomplish this, I basically abused the current built in module system. Of course I only allow levels to be loaded in a deferred way (after or before a run loop), so consider these steps happening between a run cycle.
1. Stop/Pause the game's run loop
2. Clean out current level garbage if necessary
- All image/font references are nulled out (to enable garbage collection).
- null out the global level variable created and preload references
3. I call my .loadLevel method using a string that references the level to be loaded, since I don't have the level class to specify from. This string is used to dynamically create a ig.module().requires().defines() call sort of like so:
ig.module('preloading-' + this.levelName) // A temporary preload module
.requires('game.levels.' + this.levelName) // the actual level to load
.defines(this.levelCallback); // The code to execute once all level requirements are loaded
The
.levelCallback
of course would then be used to resume the run loop, and actually load the level.
One additional piece I built was an extension of the image and font classes that are considered 'permanent'. They would maintain a different singleton that would safely allow me keep certain permanent assets, and only clear level specific stuff. Also I hacked Weltmeister to allow me to specify arbitrary assets to load on a per level basis that may not be tied to any specific entity (this includes music and sounds, for example).