Archives For RequireJS

Being able to lazy load artefacts such as controllers and directives in AngularJS is great because in addition to saving on bandwidth costs, it results in the initial load time of your AngularJS app being much shorter. This is because only the assets that are needed to render the particular route in question, are delivered to the browser, and nothing more. If too many files are being lazy loaded at a time, however, the time between the initial load of your app and when the app is actually ready to present its first route, may significantly increase. The same applies for the time it takes to change routes. This can happen when the browser has reached its ‘maximum concurrent connections’ limit and as a result, has to wait for the first set of concurrent downloads to complete before starting another set of downloads. One way to mitigate this issue is to present some sort of ‘loading’ message to the user while the lazy assets are being loaded. At times, however, the message may not be enough to maintain the perception of the app being performant. At this point, the only thing that can then be done is to combine the lazy assets into fewer files that can be delivered much faster to the browser.

This is where RequireJS comes in. RequireJS is a JavaScript file and module loader that also comes with an optimisation tool that can be used to combine module definitions into ‘optimised bundles’ for fast delivery to the browser. When partnered with Grunt (a JavaScript task runner), it can be easily used as part of your build step to package multiple lazy AngularJS artefacts into fewer files. Using the lazy loading strategy found in my previous article entitled ‘Lazy Loading In AngularJS‘, I have created a runnable sample project that demonstrates grunt being used with RequireJS to combine lazy dependencies into optimised bundles. The sample project can be found at: Note, however, that this sample project is not meant to be of production quality so please only consider it for educational purposes.