Modular JavaScript through RequireJS
The simplest way of injecting JavaScript libraries into the namespace is to add them to the HTML framework via <script>...</script>
tags in the HTML header. For instance, to add JQuery, we would add the following line to the head of the document:
<script [email protected]("lib/jquery/jquery.js") type="text/javascript"></script>
While this works, it does not scale well to large applications, since every library gets imported into the global namespace. Modern client-side JavaScript frameworks such as AngularJS provide an alternative way of defining and loading modules that preserve encapsulation.
We will use RequireJS. In a nutshell, RequireJS lets us encapsulate JavaScript modules through functions. For instance, if we wanted to write a module example
that contains a function for hiding a div
, we would define the module as follows:
// example.js define(["jquery", "underscore"], function...