Search code examples
javascriptsystemjs

how to hook into complete event of SystemJs.import?


The onready function of my webpage looks like this:

$(function(){
    importJS();
    init();
});

The importJS() function on my page looks like this:

function importJS()
{
  // set js ref path
  SystemJS.config({
    baseURL: '/js/'
  });

  //load js modules
  SystemJS.import('Init.js');   
}

The Init.js lib has an init() function but when my onready function runs, the init() function call does not find the init() function. I stepped through Chrome Dev Tools and it looks like importJS() hasn't finished loading Init.js by the time init() gets called. What's the trick to making this code work? Ie how can I ensure that SystemJS has fully loaded Init.js by the time init() gets called?


Solution

  • SystemJS.import returns a promise, the easiest way to call init() after import has finished is to return that promise from importJS() and call init() in its then callback:

    $(function(){
        importJS().then(function() {
            init();
        }
    });
    
    function importJS()
    {
      // set js ref path
      SystemJS.config({
        baseURL: '/js/'
      });
    
      //load js modules
      return SystemJS.import('Init.js');   
    }