Skip to content

Instantly share code, notes, and snippets.

@tiesont
Forked from bernos/index-with-amd.html
Created May 30, 2018 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiesont/d8c5684e9ed13c25192a9ca4325e4d6b to your computer and use it in GitHub Desktop.
Save tiesont/d8c5684e9ed13c25192a9ca4325e4d6b to your computer and use it in GitHub Desktop.
A javascript module template which supports an AMD loader (like requirejs) when available, but fails over to adding the module to a specified root context when an AMD loader is not available.
<!doctype html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<script data-main="main-with-amd" src="requirejs-1.0.4.min.js"></script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<script src="mymodule.js"></script>
<script src="main-without-amd.js"></script>
</body>
</html>
require(['mymodule'], function(MyModule) {
console.log(MyModule.sayHello());
});
console.log(MyModule.sayHello());
/**
* root is our root object context, ie. window if we are in a browser
* factory is a method that builds and returns our module
*/
(function(root, factory) {
// If AMD is available, use the define() method to load our dependencies
//and declare our module
if (typeof define === 'function' && define.amd) {
define(['dependencyOne', 'dependencyTwo'], function(dependencyOne, dependencyTwo) {
return factory(root, dependencyOne, dependencyTwo);
});
}
// Otherwise we will attach our module to root, and pass references to our
// dependencies into the factory. We're assuming that our dependencies are
// also attached to root here, but they could come from anywhere
else
{
root.MyModule = factory(root, root.dependencyOne, root.dependencyTwo);
}
})(this, function(root, dependencyOne, dependencyTwo) {
// This is our factory method. Return our module object here...
return {
sayHello: function() {
return "hello world!"
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment