Search code examples
javascripttypescriptsystemjs

Dynamic loading using systemjs, how to not load all files at once?


There is a main app.js file which has import {Route} from "./router". Router - a class that depending on the the current url of page, will create an instance of this page handler. For example, for page /home/accountPage - router will create a handler in this way: return new AccountPageHandler(params). It turns out that in the router imported all handlers of all pages (and them so much). And when I do System.import ( 'js/app.js') I will loaded all the scripts, including and unnecessary - because they are imported into the router, and the router imported in app.js.

How can I make so that does not import all at once, and only that I want to use? I am sure that this problem is already getting up earlier for many developers, but how to fix it - I have no idea because I faced with for this first time.

P.S.

My javascript is generated from the typescript (if suddenly this affects the options for solving the problem).


Solution

  • Without seeng the actual code, my guess is SystemJS imports all of your scripts because you import all handlers of all pages. What you could do (if your router supports promises and async loading of page handlers). Is to use System.import('specific_page_handler.js') to import only the page handler needed right now.

    But depending on the size of you app, and on the size of separate chunks you can lazy-load, just creating a minified bundle, setting a long cache expiration, and loading all at once can be just fine. Possibly small gains with added complexity.