Skip to content

Instantly share code, notes, and snippets.

@hns
Created November 3, 2010 15:07
Show Gist options
  • Save hns/661185 to your computer and use it in GitHub Desktop.
Save hns/661185 to your computer and use it in GitHub Desktop.
browser modules - decoupling dependency declaration and loading from module definition
// load modules passed in first argument, call function argument when loaded.
// note that modules are loaded and defined, but not yet executed (the module function is not called)
load(["single", "multi", "package"], function(require) {
// modules listed above are available via synchronous require() here.
// note that any of the modules may itself invoke load(), causing invocation of
// this function to be further delayed if the modules haven't been loaded yet
load("baz", function(require) {
// we can require "baz" here in addition to what's available outside
});
});
// defines modules with ids "foo" and "bar" - think of this as a transport optimized format
define("foo", function(require, exports, module) {
// definition of module "foo"
});
define("bar", function(require, exports, module) {
// definition of module "bar"
});
// load modules "a" and "b" belonging to this package or directory.
// No callback here, but loading will delay callbacks waiting for "package"
load(["./a", "./b"]);
// definition of module "package" itself
define(function(require, exports, module) {
// ...
});
// note that "package" here doesn't necessarily mean CommonJS package -
// it's just any group of modules used together, a directory of script files,
// anything you want to structure your app by
// defines single module with the id derived from its file name
define(function(require, exports, module) {
// definition of module "single"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment