Lazy loading external scripts in Ember
Looking through our dependencies in
bower.json I quickly found two huge offenders. We are utilizing TinyMCE as base for our “WYSIWYG”-editor and vis.js to render a nice timeline. Both these adds a few hundred kilobytes each to our
vendor.js that need to be downloaded initially for all first time users.
So how can we get around adding these dependencies to
vendor.js but still use them in our application? This turned out to be quite easy by simply adding them to the DOM in the
model-hook using a promise. I created two methods, one for js and one for css, and put them in a small utility script which can be seen below.
Then in the route where you need the script your simply import the methods and set them up as parts of your route model.
The name you give the script when loading it will be used to identify the script once loaded so it won’t be loaded again so you can reuse the same name across several routes and it will still only be loaded once.
This change saved us about 600 kilobytes on the initial load, and for users who never watch the timeline vis.js will never be loaded at all.