A better way to write and use javascript modules that will run with multiple types of module loaders.
HTML
Universal module pattern
AMD, like RequireJS
CommonJS, like Node
Browser globals
Example:
(function(global,deps,factory,root){if(typeofdefine==='function'&&define.amd)define(deps,factory);elseif(typeofmodule==='object'&&module.exports)module.exports=factory.apply(root,deps.map(function(_){returnrequire(_.split(':')[0])}));elseroot[global]=factory.apply(root,deps.map(function(_){_=_.split(':');returnroot[_[_.length-1]]}));}('myModuleName',['otherModule','underscore:_','jQuery:$'],// jQuery:$ = optional global name. "jQuery is the $ global"function(other,under,$){functionconstructor(){varresponse='response from'+other();if(!under.isUndefined(window.thing)){$('body').append($('<div> thing! </div>'));}returnresponse;}returnconstructor;},this));
Example where loader is globalised:
// In each environment in your project (e.g., Node + browser)this.unimodule=function(global,deps,factory,root){if(typeofdefine==='function'&&define.amd)define(deps,factory);elseif(typeofmodule==='object'&&module.exports)module.exports=factory.apply(root,deps.map(function(_){returnrequire(_.split(':')[0])}));elseroot[global]=factory.apply(root,deps.map(function(_){_=_.split(':');returnroot[_[_.length-1]]}));};// some-module.js(unimodule('myModule',['otherModule','underscore:_','jQuery:$'],function(other,under,$){functionconstructor(){varresponse='response from'+other();if(!under.isUndefined(window.thing)){$('body').append($('<div> thing! </div>'));}returnresponse;}returnconstructor;},this));