Revenge of the Sith was the #1 movie and Single Page Application (SPA) was coined by Steve Yen, libraries like jQuery, Mootools and Prototype.js gained traction. Other best practices took root around closures, Immediately-Invoked Function Express (IIFE 1, 2), and namespaces. Presently, almost everyone knows best practice (learn & Pluralsight ):
- No augmenting built-in native objects
- Use namespaces to prevent polluting global namespace ( Namespace.js )
- Leverage IIFE
Using namespaces isolates code, creating a sandbox of sorts to avoid name collisions and better organized code. The drawback to namespaces is verbosity and namespace cluttering. As applications grow deep nested namespaces
(FrozenBytes.Common.ServiceProxy.doAjaxPost(method, ..)) are common, sparking an urge to put all methods into a single object. All methods on a single object are a red flag, name collisions will increase. Even using noConflict() is error prone. Race back to current day, 2013, the year of
Iron Man 3 and release of VS 2013 forget all of this mess, instead work with a module system.
load require.js, add an entry point using
add configuration for custom and/or third party scripts then begin using the require or define to asynchronously load scripts and modules. Implementing in a SPA is straight forward as seen below. What about multi-page applications? Before you say this won’t work in a traditional multi-page applications like ASP.NET MVC or even TypeScript, hold your tongue. While this is out of scope for this article please visit the references below or reach out to me via email@example.com.
- ASP.NET MVC 4 and RequireJS
- Using RequireJS in an APS.NET MVC application
- Bootstrap Require.js inside
index.htmlby adding a script tag, then define the main entry point of the application using data-main HTML5 attribute,
- Configure Require.js using
require.config, define properties, paths specifying versions and/or shims to load non AMD modules.
- Define a module with no dependencies, add an anonymous function called
utilto return the sum of two numbers. Best practice is a 1:1 mapping between a module and physical file; file named util.js to match the module.
- Define an app module with a dependency on util module. Use util module to return
app.js runfunction. Require.js will load App.js in the main.js file.
- Wire-up app.js module with Require.js using the
mian.js. Behind the scenes Require.js loads, injects the dependency chain with proper scope relative to the root as dependencies to the function enabling execution of
A more complex example:
- Define modular dependencies for the function. RequireJS will inject system.js, logger.js, router.js, and config.js relative to root as dependencies to the function.
- [GitHub requirejs.demo][https://github.com/segilbert/requirejs.demo]