The "on-demand" approach to deploying JavaScript applications incrementally confers great benefits, but nontrivial use can pollute functions with expressions that are unrelated to their essential nature. Aspect-Oriented Programming (AOP) can resolve this problem completely; yet AOP in JavaScript is an unexplored area of web development. In this article, I show the need for such techniques in web development, and explain the principles of function interception in JavaScript. In short, I present an elegant technique for loading JavaScript libraries transparently at the point of need.
JavaScript Library Inclusion
JavaScript programs are associated with HTML documents by means of script elements where, in the simplest case, opening and closing <script> tags delimit the JavaScript syntax embedded within a page. However, many pages may require the same functionality, and this mandates placing the relevant code in discrete files that bear a .JS extension. Such libraries can then be pulled into the execution environment by specifying the file name as the value for the src attribute in an empty <script> element; see Listing One.
<html> <head> <script type = "text/javascript" src = "MyLib.js"></script> </head> <body> ... </body> </html>
JavaScript's interpreted nature aside, this is identical to the #include mechanism supported by C/C++, but the Pareto principle (en.wikipedia.org/wiki/Pareto_principle) also indicates the seeds of trouble. Generally, 90 percent of a program's runtime is spent executing only 10 percent of its code, implying that functionality should be loaded into the execution environment only when needed lest resources be consumed redundantly. Compiled applications accommodate this by using DLLs, but without similar intervention a client-side JavaScript application can download large tracts of code that are never actually executed.
Such inefficiency should be avoided assiduously in web deployment; it consumes bandwidth unnecessarily, increases download times, and stresses both server and client needlessly. The poor performance that results can render an otherwise competent application unpopular if not unusable, and this concern can only grow as web developers become ever more adventurous in their use of JavaScript.