My angular 2 app takes a long time to load for first time users, I need help to speed it up
To have something ready for production (and speed it up), you need to package it.
I mean transpiling all files into JavaScript ones and concat them the same way Angular2 does for example. This way you will have several modules contained into a single JS file. This way you will reduce the number of HTTP calls to load your application code into the browser.
As a matter of fact, for the following configuration of SystemJS, you will have one call per module (it's suitable for development but not really efficient in production):
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
This answer could give hints about how module resolution works:
- How does Angular2 resolve imports?
You can do this packaging using Gulp and its plugins:
- https://www.npmjs.com/package/gulp-tsc
- https://github.com/contra/gulp-concat
See the following answers:
- Using Gulp to Concatenate and Uglify files
- https://github.com/JavascriptMick/angular2-gulp-typescript/blob/master/gulpfile.js
Though late, for people comming here now...if you are using angular2+ then try
ng build --prod --env=<staging or prod or your env file>
It will do AoT, bundling cache busting and minification all in one command.
More deatils can be found in Angular official website in ng build
section. In my case one of the chunk
was actually 2.4MB which was reduced to 450+KB but after including --prod
it was further reduced to 200+KB
Good size for an app depends. Angular2 has the concept of lazy loading of code or chunking. You can split your app into chunks (like admin UI and user UI) and load them on demand so that the entire app need not be loaded initially which will help in reduced load time. The following articles could be of extra help:
- https://blog.waffle.io/code-splitting-in-angular-2-with-webpack-2-ce8dd4b8b23e
- http://blog.rangle.io/optimize-your-angular2-application-with-tree-shaking/
- http://blog.mgechev.com/2016/06/26/tree-shaking-angular2-production-build-rollup-javascript/
I ran into this same problem, basically you just need to run the webpack build in production mode.
To do this install webpack globaly npm install webpack -g
Once installed, run webpack -p
from your apps root directory. This brought my file size down from over 5MB to about 700KB