The JavaScript blog.


tutorials frameworks lmaf amd

Supporting AMD and Script Tags

Posted on .

Let's Make a Framework is an ongoing series about building a JavaScript framework from the ground up.

These articles are tagged with lmaf. The project we're creating is called Turing. Documentation is available at turingjs.com.

Last week I started retrofitting Turing with AMD (Asynchronous Module Definition) support. This week I'll complete most of this conversion to AMD by demonstrating how to use AMD modules both with and without a script loader.

Backwards Compatibility

James Burke, creator of RequireJS, contributed to Dojo's script loader. As we've seen previously in this series, Dojo ships with a resource loader that's capable of loading AMD modules, and is in fact built upon AMD. In contrast, jQuery conditionally supports AMD if a define function exists.

I wanted to do something slightly different: use define to express module dependencies, but still allow people to include Turing modules on a page without using a script loader. All modules are dependent on turing.core, and some are dependent on the dom and events modules. Turing contains some useful Underscore-like functionality in the turing.enumerable module, and I've always avoided reusing it in other modules because there wasn't a way of expressing the dependency.

Therefore, I want Turing to be structured using AMD and to support these use cases:

  • Load modules with script tags
  • Use a monolithic, optionally minimised, build of the entire framework
  • Load Turing modules with a script loader

This means we need an alternative method to jQuery's conditional AMD support. Dojo's built-in script loader is another solution, but it's actually a huge amount of work and people might not always want to use a script loader.

So, what do we do? There are a few ways to approach this problem:

  1. Make the build process change calls to define to work without a script loader
  2. Force people to use a script loader
  3. Patch define when not available

The first option seems like it would require too much maintenance -- people would have to choose an AMD Turing download or a non-AMD version. The second option allows us to build Turing using AMD's nice, modular structure, but completely breaks backwards compatibility. The third option has potential, and this is the one I spent some time exploring.

Patching define

To support AMD's define method when an AMD-compatible script loader isn't available, I added a method to turing.core:

// turing.core.js
(function(global) {
  var turing = {}, modules = {};

  // `turing.core`'s code goes here

  turing.define = function(module, dependencies, fn) {
    if (typeof define === 'function' && define.amd) {
      define(module, dependencies, fn);
    } else {
      if (dependencies && dependencies.length) {
        for (var i = 0; i < dependencies.length; i++) {
          dependencies[i] = modules[dependencies[i]];
      modules[module] = fn.apply(this, dependencies || []);

  // Export `define``
  if (typeof define === 'undefined') {
    global.define = turing.define;
}(typeof window === 'undefined' ? this : window));

// turing.dom.js
define('turing.dom', ['turing.core'], function(turing) {  
  // `turing.dom` source

By wrapping each module in a define statement, individual modules can now be loaded using RequireJS, and they'll automatically load turing.core:

require(['turing.anim'], function(anim) {  
  turing('#results').html('Turing has loaded with the DOM module.');
  turing.anim.chain(turing('#animate')[0]).move(1000, { x: '100px', y: '100px', easing: 'ease-in-out' });

The turing function here is the global turing method that will get exported to window. The turing.anim module has turing.core as a dependency, so we get the familiar turing function as expected.

This snippet is used by a functional test that I wrote to ensure Turing modules can be loaded with RequireJS. It's a small Express app that can be found in test/functional/require.js.


jQuery is currently a monolithic framework (although the build process can be customised to remove unwanted libraries) which makes supporting AMD relatively easy. Conversely, Dojo is highly modular -- it's built on AMD and includes its own module loader.

Here I've presented an alternative solution that uses a lightweight version of AMD's define method to support module loading through script tags, monolithic files, and AMD-compatible script loaders. It's a potentially useful pattern for structuring large libraries and frameworks that have interdependent modules.

The code for this tutorial can be found in commit 4361042.


tutorials frameworks lmaf amd

Retrofitting AMD

Posted on .

Let's Make a Framework is an ongoing series about building a JavaScript framework from the ground up.

These articles are tagged with lmaf. The project we're creating is called Turing. Documentation is available at turingjs.com.

Last week I looked at how AMD (Asynchronous Module Definition) works and how projects use it. This week I'm going to show how to retrofit it to an existing project, in this case our Turing framework, and hopefully you'll be able to apply this to your own reusable client-side JavaScript.

Redefining Modules

Turing's modules were structured around Immediately-Invoked Function Expressions (IIFEs), with CommonJS module loading support. AMD supports CommonJS modules, and Node can work with AMD too.

The core Turing module can be defined as an AMD module like this:

define('turing.core', [], function() {  
  var turing = function() {};

  // Core functionality added here

  return turing;

A module loader is now needed to use this code in a browser. RequireJS works like this:

require(['turing.core'], function(turing) {  

The methods in turing.core.js will be available once RequireJS has loaded the script.


A good reason for using AMD is dependencies can be specified and resolved by loaders. In Turing, every module depends on turing.core. That means the DOM module would have to be updated to look like this:

define('turing.dom', ['turing.core'], function(turing) {  
  var dom = {};
  // DOM module defined here
  return dom;

Previously, expressing dependencies between modules wasn't possible outside of code comments. Dependencies make it easier to break down functionality into smaller reusable chunks and loaded when required.

 Loading the Entire Framework at Once

When using frameworks like jQuery, many projects need a broad selection of functionality and therefore load the entire library rather than parts of it. Rather than forcing users to use require or define invocations with a large amount of dependencies, it's possible to offer a broad selection in one file.

I've created a turing.js file that contains the following:

define('turing', ['turing.core', 'turing.dom', 'turing.anim'], function(core, dom, anim) {  
  core.dom = dom;
  core.anim = anim;
  return core;

These are the modules that I've ported to work with AMD so far, but I'll add all of them under turing.js once I've finished.


What about building a monolithic, minified version of Turing? RequireJS addresses this by including the RequireJS Optimizer. This basically boils down to:

> npm install requirejs
> r.js -o app.build.js


I've started adapting Turing to work with AMD, and my early tests work with RequireJS. However, I'm finding it difficult to get builds to generate with r.js (it seems like the current release has bugs).

Although using AMD's well-defined module pattern and dependencies solves certain problems when developing reusable code, it makes it difficult to satisfy users who simply want to include a library using a script tag without a module loader like RequireJS. I've been experimenting with creating a small define function that is used when a module loader isn't available, and I'll cover that in next week's tutorial.


tutorials frameworks lmaf amd

The How and Why of AMD

Posted on .

*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

In Improving Client-Side
I talked about
better ways to load modules, and showed how jQuery supports the
Asynchronous Module Definition (AMD) API. As open source developers, supporting this specification makes it easier for others to
reuse our code. It also helps resource loading frameworks like

In the Let's Make a Framework series, we've already covered Common JS
and seen how they
can make our code accessible for Node developers. However, implementing
a convincing client-side version of this is difficult because
require is generally implemented as a synchronous
statement. There are projects to wrap this for browser-based
development, but AMD offers a native solution that's easy to work with.
This is where AMD steps in as a "transport format".

Conditional AMD Support

jQuery provides conditional AMD support. When writing smaller, tightly
focused libraries, this is a useful approach because it allows AMD to be
supported where available. jQuery checks for the existence of
define, and this approach can be reused:

var myModule = {
  awesome: 'not really'

if (typeof define === 'function' && define.amd) {
  define('myModule', [], function() {
    return myModule;

The amd property is explained by the AMD specification:

To allow a clear indicator that a global define function (as needed for script src browser loading) conforms to the AMD API, any global define function SHOULD have a property called "amd" whose value is an object. This helps avoid conflict with any other existing JavaScript code that could have defined a define() function that does not conform to the AMD API.

We need to check for both the define function, and that it
conforms to the specification.

Internal AMD Use

Another approach is to build an entire project around AMD.
Dojo was restructured to work this way. This comment is from Dojo's source:

This function defines an AMD-compliant loader that can be configured to operate in either synchronous or asynchronous modes.

Then modules are wrapped with define:

define(["./_base/kernel", "./_base/lang", "./_base/Color", "./_base/array"], function(dojo, lang, Color, ArrayUtil) {


Notice how dependencies in AMD are the same order as the callback (or
"factory function", as the AMD specification refers to it). This is explained in the specification:

[...] the resolved values should be passed as arguments to the factory function with argument positions corresponding to indexes in the dependencies array.

As I mentioned in Improving Client-Side Modularity, Kris Zyp
documented this move to AMD in Asynchronous Modules Come to Dojo

CommonJS Wrapping

The AMD specification also addresses CommonJS modules with this example:

define(function(require, exports, module) {
  var a = require('a'),
      b = require('b');

  exports.action = function() {};

The RequireJS documentation points out that this can help with cases
where there are a lot of dependencies:

define([ 'require', 'jquery', 'blade/object', 'blade/fn', 'rdapi',
         'oauth', 'blade/jig', 'blade/url', 'dispatch', 'accounts',
         'storage', 'services', 'widgets/AccountPanel', 'widgets/TabButton',
         'widgets/AddAccount', 'less', 'osTheme', 'jquery-ui-1.8.7.min',
         'jquery.textOverflow'], // ...

This is difficult to read. The RequireJS documentation goes on to say
that using require is potentially easier to follow. An AMD
module loader has to parse out the require calls and insert
the define dependencies transparently.

Since the authors of RequireJS have experience implementing such things,
they're all too aware of browser inconsistencies and limitations:

Not all browsers give a usable Function.prototype.toString() results. As of October 2011, the PS 3 and older Opera Mobile browsers do not. Those browsers are more likely to need an optimized build of the modules for network/device limitations, so just do a build with an optimizer that knows how to convert these files to the normalized dependency array form, like the RequireJS optimizer.

This means a pre-compilation step may be necessary to support a broad
range of browsers using this approach.


If you've followed our previous tutorials on building an asynchronous
script loader, you'll know that writing JavaScript APIs for loading
scripts isn't trivial. Supporting CommonJS isn't necessarily difficult,
but supporting features like parsing require calls is where
things get tricky.

This leads us to an important point that must be considered when
building our own libraries and frameworks: should we ship our own script
loading solution, or conditionally support AMD? Given the complexity of
building a script loader, it may be better to conditionally support AMD
as jQuery does.

This doesn't quite satisfy our needs for Turing, however. Turing does
have one or two modules that are dependent on each other, and
define provides a way to express this programatically. It
may be better to use define to wrap modules, as we already
do using an IIFE (Immediately-Invoked Function Expression), and
effectively no-op it if it isn't present.

Next week I'll look at adding AMD to Turing, then test it out with



tutorials frameworks testing lmaf

Improving Client-Side Modularity

Posted on .

*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

When I started writing Turing I said I wanted to keep the modules
decoupled so parts of the framework could be used in isolation. Most
popular web frameworks package a large chunk of core functionality that
includes support for everything from a selector engine to event handling
and ajax.

I think it's fair to say that this convention has now changed, and
people want to be able to cherry pick parts of a framework alongside
other libraries. And what's more, this can't just be addressed by a
build process because some projects might load scripts with a
RequireJS style library, or by concatenating and minifying all of their client-side JavaScript using a server-side

With that in mind, can Turing truly be considered modular? If it is
indeed modular, then this should be possible:

  Let's Make a Framework: Modularity

    Test Content

assert.equal(turing('#test p').html(), 'Test Content');

  .css({ backgroundColor: 'green', color: 'white' })
  .html('Test Passed');

I tried this little test and it worked. Each Turing module is split into
Immediately-Invoked Function Expressions (IIFE) that depend on the
existence of a 'turing' global variable:

// turing.core.js
(function(global) {
  if (global.turing) {
    throw new Error('turing has already been defined');
  } else {
    global.turing = turing;
    if (typeof exports !== 'undefined') {
      exports.turing = turing;
}(typeof window === 'undefined' ? this : window));

// turing.dom.js
(function() {
  var dom = {};

  turing.dom = dom;

This pattern isn't ideal however, it's simply what I used to keep the
initial tutorials focused on their specific subjects. A better solution
would be to embrace the Asynchronous Module
(AMD). Rather
than trying to deal with CommonJS modules in browsers, or by using a
framework-specific solution, embracing AMD yields several advantages.

Supporting AMD

I've already demonstrated how client-side projects support
, and supporting
AMD projects is very similar. Some well-known projects already support
it, and the RequireJS site has a great post with a list of these
projects here: Why AMD?.

jQuery does it like this:

(function( jQuery ) {

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
    define( "jquery", [], function () { return jQuery; } );

})( jQuery );

Let's break that down to see how it works. If define
exists, then set up a module named "jquery" with no dependencies. AMD is
based around the module pattern, so a function is used as
define's third parameter that returns the jQuery function.
I've edited the original file for the purpose of publication, but the
(exports.js) has a lengthy comment explaining just about everything here. For
example, the module is registered as "jquery" because AMD derives module
names from file names, and jQuery's file name is usually lowercase.


From a client-side developer's perspective, AMD is a more friendly way
to manage JavaScript modules when compared to CommonJS
. It helps us to
avoid creating unnecessary global variables, and helps support
client-side script loading libraries.

It may even be worth considering structuring entire frameworks around
it, so modularity goes right into the core of the project. As the
interest grows in projects like jquip,
it seems obvious that there is a need for more granular client-side
frameworks, and AMD gives us the tools to make that happen in an open
and reusable way. If you take a look at
Dojo source, you'll see that it already works this way. This was documented in Asynchronous Modules Come to
Dojo 1.6
, which
explains AMD's implications for a large project like Dojo.



tutorials frameworks testing lmaf

Managing Asynchronous Assertions

Posted on .

*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

The biggest problem I've had when writing tests for Turing is checking
when asynchronous callbacks complete. For example, when testing the
resource loading feature, I wrote tests with this pattern:

'test queue loading with no local scripts': function() {
  ]).on('complete', function() {
  }).on('loaded', function(item) {
    if (item.src === 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js') {
      assert.ok(jQuery, 'jQuery should be set');

What happens if loaded never fires? Well, the test would
still pass. That's a consequence of the assertion never being run.

One solution is to wrap the assert module with counters
that count how many assertions have been called. Then at the start of a
test we can write assert.expect(2); to say 'raise an error
if anything other than two assertions are run'.

That's fine, but at this point Turing's test framework always runs tests
asynchronously. If the assert module kept a counter, other
tests would increment that value too. The number of assertions would be
the total number for all of the current suite's tests, rather than the
current test.

Counting Assertions

The initial solution I came up with was to wrap every assertion method
with a function that incremented a counter. Tests take this pattern:

'test queue loading with no local scripts': function() {
  var assertExpect = mixinExpect(assert);

  ]).on('complete', function() {
  }).on('loaded', function(item) {
    if (item.src === 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js') {
      assertExpect.ok(jQuery, 'jQuery should be set');

Each test gets its own instance of the assert module.

The code to do this is slightly clumsy, because I aliased the old
methods using a ** prefix:

function mixinExpect(m) {
  var m2 = {}, method;

  for (method in m) {
    if (m.hasOwnProperty(method)) {
      m2['__' + method] = m[method];
      (function(methodName) {
        m2[methodName] = function() {
          m2['__' + methodName].apply(m2, arguments);

  m2.expect = function(count) {
    m2.mixinExpectAssertionCount = 0;
    m2.mixinExpectExpected = count;

  m2.done = function() {
    if (m2.mixinExpectAssertionCount !== m2.mixinExpectExpected) {
      throw('Expected assertion count was not found, expected: ' + m2.mixinExpectExpected + ', got: ' + m2.mixinExpectAssertionCount); 

  return m2;

It does the job, but is there a more elegant way that doesn't require
changing the assert module?


I got this idea when I reviewed Tim Caswell's

'test queue loading with no local scripts': function() {
  var expect = new Expect();
  expect.add('jQuery was set');
  expect.add('loaded fired');

  ]).on('complete', function() {
    expect.fulfill('loaded fired');
  }).on('loaded', function(item) {
    if (item.src === 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js') {
      expect.fulfill('jQuery was set');
      assert.ok(jQuery, 'jQuery should be set');

Each test creates an instance of Expect and adds a list of
expectations. As the expectations are fulfilled, it marks down this
fact, then at the end of the test when expect.done() is
called it can see if any expectations were unfulfilled.

I made a quick implementation and it's only a few lines of code:

function Expect() {
  this.expectations = {};

Expect.prototype = {
  add: function(expectation) {
    this.expectations[expectation] = false;

  fulfill: function(expectation) {
    this.expectations[expectation] = true;

  done: function() {
    for (var expectation in this.expectations) {
      if (!this.expectations[expectation]) {
        throw('Expected assertion was fulfilled , expected: ' + expectation); 


Working with asynchronous tests can quickly get confusing -- sometimes
tests appear to be passing but aren't actually running as expected. The
CommonJS Unit Testing spec actually says the following:

The assertions defined above will not be to everyone's taste style wise (or infact behaviour wise.) Authors are free to define their own assertion methods in new modules as desired.

So adding a assert.expect method to your own assertion
module implementations is perfectly acceptable.

This week's code can be found in the ajax tests in commit