A Note on Script Loaders

It’s difficult to discuss AMD and CommonJS modules without talking about the elephant in the room: script loaders. At the time of writing this book, script loading is a means to a goal, that goal being modular JavaScript that can be used in applications today—for this, use of a compatible script loader is unfortunately necessary. To get the most out of this section, I recommend gaining a basic understanding of how popular script loading tools work so the explanations of module formats make sense in context.

There are a number of great loaders for handling module loading in the AMD and CommonJS formats, but my personal preferences are RequireJS and curl.js. Complete tutorials on these tools are outside the scope of this book, but I recommend reading John Hann’s article about curl.js and James Burke’s API documentation RequireJS for more.

From a production perspective, the use of optimization tools (like the RequireJS optimizer) to concatenate scripts is recommended for deployment when working with such modules. Interestingly, with the Almond AMD shim, RequireJS doesn’t need to be rolled in the deployed site, and what one might consider a script loader can be easily shifted outside of development.

That said, James Burke would probably say that being able to dynamically load scripts after page load still has its use cases, and RequireJS can assist with this, too. With these notes in mind, let’s get started.

Get Learning JavaScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.