How to use asynchronous modules in the browser
To get a grasp on AMD, we will do a few examples. We will need script loader RequireJS (http://requirejs.org/docs/download.html). So you can download it and then address the local version in your HTML or give it an external link to CDN.
First of all, let's see how we can create a module and request it. We place the module in the foo.js
file. We use the define()
call to declare the module scope. If we pass an object to this, the object simply gets exported:
foo.js
define({ bar: "bar", baz: "baz" });
When we pass a function, it is called and its return value is exported:
foo.js
define(function () { "use strict"; // Construction return { bar: "bar", baz: "baz" }; });
Next to foo.js
, we place main.js
. This code can be described as follows: call the given callback when all the modules supplied to the first argument (here only foo
, which means ./foo.js
) are loaded and available...