Mastering Web Application

(Rick Simeone) #1
Chapter 12

AngularJS and Asynchronous Module Definition

Asynchronous Module Definition (AMD) specification, popularized by Require.
js and similar JavaScript libraries, aims to create a set of rules to be followed by
reusable JavaScript modules that can be loaded asynchronously. AMD modules can
be loaded on demand, taking inter-module dependencies into account. Alternatively,
AMD module definitions can be used by an offline-build script to prepare a
combined version of all the modules needed for the proper application functioning.


AngularJS has its own module system. While both AngularJS and the AMD
specification use the word "module", the same word is used to mean two different
things, which are as follows:



  • AngularJS modules define how different JavaScript classes and objects
    should be combined together during application runtime. AngularJS
    modules don't enforce any script loading strategy. On the contrary,
    AngularJS expects that all modules are loaded into a browser before an
    application can be bootstrapped

  • AMD modules are mostly concerned with scripts loading. The specification
    allows you to break down your application into several smaller scripts and
    load only the needed parts asynchronously, on-the-fly, when needed.


AngularJS modules and AMD modules address different problems and, as such,
shouldn't be confused.


In the current version (1.1.x), AngularJS expects that all the scripts making up an
application are loaded into a browser before an application is kickstarted. In this
setup there is no room for asynchronous, on-demand modules containing application
code. It is simply not possible to register new modules nor providers (services,
controllers, directives, and so on) after AngularJS application was initialized.


In the current version of AngularJS asynchronous loading of AMD
modules can be only used to load JavaScript libraries and application
code upfront, before the application is initialized. Loading of additional
application code on-the-fly, when needed, is not currently supported.

Lack of on-demand loading of AngularJS modules might sound like a big limitation,
but once again, we need to evaluate it in the right context. The AMD modules were
created to address several concerns, which are as follows:



  • Loading scripts asynchronously, so that a browser is not blocked and can
    load several different resource types in parallel.

Free download pdf