Skip to content

Instantly share code, notes, and snippets.

@cuth
Last active April 22, 2017 20:47
Show Gist options
  • Save cuth/99902bbcc88485328916 to your computer and use it in GitHub Desktop.
Save cuth/99902bbcc88485328916 to your computer and use it in GitHub Desktop.
Mixing an AMD script loading solution with a traditional script loading solution with UMD modules causes a conflict.

Using RequireJS and loading UMD scripts normally

Mixing an AMD script loading solution with a traditional script loading solution with UMD modules causes a conflict.

Two approches to loading scripts

The traditional way to load a script is to manually add a script tag on the page like this:

<script src="/path/to/file.js"></script>

These scripts and loaded synchronously and the script is parsed after it is loaded.

The AMD approach to script loading uses one script tag to load a "modular script loader" (like RequireJS) then using that load any subsequent scripts.

Creating a module

When creating a module, for maintainabililty purposes, most modules support both AMD and the traditional way of loading scripts. The most common way of supporting both methods in the same javascript file is to use the UMD method.

UMD has code that looks like this:

if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['b'], factory);
} else {
    // Browser globals
    root.amdWeb = factory(root.b);
}

More examples here

How UMD works is that it will detect AMD and assume it is being loaded through an AMD loader and use the define call. If AMD is not detected then it will assume the script was loaded in the traditional way and assign a browser global.

The problem

UMD does not expect to be loaded traditionally when AMD exists. When UMD loaded traditionally detects AMD it will use a define call which will cause an error because it was not loaded through AMD.

From the RequireJS docs:

If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

This does not mean that anonymous defines are bad. Anonymous defines are used all the time when the module is loaded through an AMD loader.

This makes it impossible to use any UMD script loaded traditionally when AMD has also been added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment