Search code examples
javascriptasynchronousecmascript-6createjs

CreateJS using ES6 modules


I'm using createJS - preloadJS and ES6 along with Babel and webpack.

const files = [{ src: 'characterSprite.png', id: 'characterSprite' }];

const Loader = new createjs.LoadQueue(false);
Loader.loadManifest(files, true, 'img/');

export default Loader;

What I want to achieve is in preload.js to load all the images, and in other files (eg. hero.js) to do something like:

import Loader from './loader';
Loader.getResult('characterSprite');

The thing is that when I call .getResult() on loader, the loader has not finished preloading so it returns undefined.

I can check when loader is finished by using:

Loader.addEventListener('complete', () => console.log('loader has finished');

My question is if I can export the module only if the loader has finished?

Is there a better way of doing this?


Solution

  • I'm not familiar with CreateJS, but this should be plain old ES6 (eh), so you could solve this by wrapping the Loader and start it after importing it:

    class MyLoader {
        constructor(files) {
            this.files = files;
        }
    
        load() {
            // Using a promise is optional, but I would recommend it
    
            return new Promise((resolve) => {
                 const Loader = new createjs.LoadQueue(false);
                 Loader.loadManifest(files, true, 'img/');
    
                 Loader.addEventListener('complete', () => { resolve(Loader) });
            });
        }
    }
    
    export default MyLoader;
    

    This way you could instance run it like this:

    import MyLoader from './MyLoader';
    const files = [{ src: 'characterSprite.png', id: 'characterSprite' }];
    
    let myLoaderInstance = new MyLoader(files);
    myLoaderInstance.load().then( (completedLoader) => {
        console.log('Loader has finished!', completedLoader.getResult('characterSprite') );
    } );
    

    Does this make any sense? :)

    EDIT: You also might want to look into Webpack's file-loader, which allows you to require images like you would with JS modules, so that they get bundled with the rest of your code. It doesn't have anything to do with runtime image loading, but it's very handy nonetheless!