Tutorials JavaScript JavaScript Module Loaders

JavaScript Module Loaders

Web "apps" are slowly becoming the norm on the internet. Websites are not just for show anymore and developers have starting adding a lot of interactivity; you can watch movies, play games, voice and video chat. You can do on your browser what used to require an actual program.

What is a module?

Short Version:

It's a plugin.

You've downloaded JavaScript plugins before where you link the to file with a <script> tag and then call the plugin with something like $('#slider').bbslider();. That's a module, in spirit if not in name.

Long Version:

A module is a set of functions that accomplish one particular goal. When you build a website, you could have many different JavaScript features. You could have a JavaScript slider, image gallery, and menu animations on the same website. Module loaders attempt to organize your plugin's functionality for portability and maintainability. It keeps everything in its own local scope and its own set of files. Your main script calls public functions from that plugin, but will never try to "patch" features into it.

The biggest difference between modules and normal JavaScript plugins is that modules define dependencies so you don't have to worry about load order. The slider needs jQuery, the search needs AngularJS, the pop-up needs Bootstrap, the chat needs NodeJS, ect. It's easy to remember when all you need is jQuery, but if you have website that also uses MooTools, Bootstrap, Prototype, AngularJS, and plugins that require other plugins, it's easy to forget the load order and then you get the infamous "x is undefined" error.

Now you know how the daycare worker feels caring for ten kids with different allergies.

Can I start my module development today?

Let's get the elephant out of the room first. Currently, no browsers on the market, not even the modern ones, support module loading. The standard has been finalized in EMCAScript 6 but it will be at least another year before the browsers actually support it. If you want to develop modules today, you're going to need a module loader. RequireJS is probably the most popular option if you're doing web-based coding for browsers.

AMD vs CommonJS vs EMCAScript 6

Asynchronous Module Design (AMD) loads JavaScript asynchronously, which means it loads one file after another. You need to load the jQuery library before you can use jQuery plugins. Browsers use this method to load JavaScript. RequireJS module loader utilizes this method.

CommonJS (CJS) loads JavaScript synchronously, which means it loads everything ASAP. Node.JS utilizes this method. It's mostly used for server-side JavaScript.

EMCAScript is the JavaScript standard. EMCAScript 6 (ES6), also known as EMCAScript 2015, officially supports module loading. This means that browsers will (eventually) support module loading without 3rd party plugins.

How do I change my current jQuery plugin into an AMD module?

You're going to have to rework your entire code structure and chop it up into pieces. Separate your next, prev, transitions and callback functions should each be their own module.

define(['jquery'],function($) {
  
  var myFunc = function() {
    // function code here
  };
  
  return {
    myFunc: myFunc
  };
});

You can view the JavaScript module demo where I pass a jQuery object to a module on click.

Why use AMD or CJS if ES6 is coming out soon?

I'm still waiting for Valve to release Half Life 3 "soon." In all seriousness, and I'm probably going to get flamed hard for saying this, but in my opinion you should skip straight to ES6 and don't waste time learning CJS or AMD. There are JavaScript translators, like Babel, which can automatically transform ES6 code into AMD or CJS.

You can develop ES6 modules, use Babel to translate it into AMD, run it through RequireJS, and have it working today. When the day comes that browsers finally have support, you can just remove RequireJS and use your ES6 code right in the browser. Imagine telling your developer friends that you're fully utilizing the browser's newest and coolest features on the day of release.

One last note: caching

Story of my life:

On my first day playing with RequireJS, making my first app, first initial test run, I got an error, not surprisingly. Then began the debugging process; tried one fix after another, nothing worked. Finally in my frustration after tearing my hair out, I deleted the chunk of code that was giving me the error. I expected it to break somewhere else, but to my surprise, I still got the same error. It was on the same line, on the same function, that wasn't even there; ghost code that I hit the delete button on was giving me an error.

It finally dawned on me that my JavaScript was cached. Normally, the cache is flushed on browser refresh, and I was refreshing the browser after every code update. RequireJS has some sort of deep caching feature that stays between refreshes. The easiest way to make sure the cache is cleared is to add a query string to the end of the URL, which RequireJS has an option for. All you have to do is add urlArgs: "bust=" + Math.random() to your RequireJS configuration. Just remember to turn it off before deploying to production.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.