T
he principles of good software-design hold that methods
should do one thing alone, rather than conflate disparate functionality. Yet the
conventional approach to 'on-demand' JavaScript commits that very sin by polluting methods
with code for retrieving resources from the server. Ideally, on-demand loading should
occur without such disjunctive clutter, and this page explains how to employ AspectJS to this effect.
Contents
To use the approaches demonstrated below, you must have a copy of AspectJS, which can be downloaded for free
from the
Download page. A comprehensive and
detailed
tutorial is also available, and you are strongly advised to
read the
Getting Started page before reading this one.
Additionally, the examples below use three functions called
LoadStyleSheet,
LoadLib_STH and
LoadLib_XHR.
The code for these, and instructions for using them independently from AspectJS can be found on their respective pages.
Note that if you wish to use
LoadLib_XHR you will also need a copy of the
XMLHTTPRequest library that is also available on this site.
Alternatively, you can use proprietary versions of all these resources.
For a detailed explanation of the rationale behind the techniques explored below, see the article entitled
Transparency on Demand, which appeared in the
November 2007 edition of Dr Dobbs Journal of Programming.
Core Principle
Transparent on-demand loading pivots on the notion that calls to retrieve code from the server can be removed from
functions that make such calls, and can be applied instead as prefixes to those functions. In other words,
invocation of a given function can be intercepted, such that a call to a library-loader executes first, followed by execution
of the interceptee. This removes disjunctive syntax from the interceptee, thus restoring its cohesion.
Critically, and in the case of loading JavaScript (rather than CSS code), a given library need be retrieved only once, as
the code it contains remains in the execution environment until a new page is loaded. AspectJS gives control over
affix lifetime, therefore a 'loading prefix' can be set to execute just once before it is removed, thus improving
efficiency even further.
Further to this, all prefix-related code can be placed in a library that is separate from all other code in the system,
and this underlines the essential tenet of Aspect Orientation, which is that non-related, but cross-cutting concerns
can be separated out, thus aiding the implementation and development of a system.