SlideShare a Scribd company logo
1 of 18
Asynchronous Module Definition (AMD)

The missing client-side JavaScript module system.
about me

Martin Stadler
| Frontend engineer /
  JavaScript developer @ excentos
| Web developer since 2004
  (HTML/CSS, PHP, Python, Drupal,
  Plone, jQuery, …)
| Developing modular
  single-page apps since 01/2010


| Email: martin@siarp.de
| Twitter: @xMartin
excentos – what we do

Product Advisors
| Web apps to find the
  right product for you
| Goal: to perform like a
  human sales expert
| Single-page JavaScript,
  Dojo Toolkit
Overview

Asynchronous Module Definition (AMD)
| Motivation
| Modules
| Loading
| Optimization
| Conclusion
| Questions/Discussion
Motivation

| Pages turn into apps
     ●   More code
     ●   More complex
     ●   Serious development, not just a few lines of script
| Design principles
     ●   Separate into reusable components
     ●   Avoid global namespace pollution
What is a Module?

Manual dependency resolution
   <head>
       <script src="myLib.js"></script>
       <script src="myLibPlugin.js"></script>
       <script src="mySpaghettiCode.js"></script>
   </head>
What is a Module?

JavaScript module pattern
   var mymodule = (function() {
       var a = 'x',
           doSth = function(){...};

       return {
           getA: function() {
               return doSth(a);
           }
       };
   })();


Where does it live?
| Global? At least reusable.
| Closure? Closure of what?
What is a Module?

| module = resource
| declares dependencies
Python
mymodule.py                app.py
                                                     $ python app.py
 def printSth():            import mymodule
                                                     sth
     print 'sth'
                            mymodule.printSth()



NodeJS
mymodule.js                app.js
                                                     $ node app.js
 exports.printSth =         var mymodule =           sth
 function() {               require('./mymodule');
     console.log('sth');
 };                         mymodule.printSth();
What is a Module?

AMD

mymodule.js                app.js                 index.html

define(function() {        define([               <script
                             "mymodule"           src="loader.js"></script>
return {                   ], function(myMod) {   <script>
  printSth: function() {                          require(
    alert("sth");          myMod.printSth();        ["app"],
};                                                  function(app) {
                           });                        // if app returned
});                                                   // something, we'd use
                                                      // it here...
                                                    });
                                                  </script>
AMD

| Asynchronous
      ●   Don't block browser
      ●   Parallel download and interpretation
      ●   Callbacks everywhere...
| Loaded via script tag injection (not XHR + eval)
      ●   Debugging
      ●   X-Domain
Loader Plugins

define([
  "../Widget",
  "text!./tpl.html"
], function(Widget, tpl) {

return new Widget({name: "mainApp", template: tpl})

});


| text!
      ●   Load via XHR
      ●   E.g. templates for widgets, data
Load non-modules

require([
  "dir/foo.js",
  "http://host/script.js"
], function(/*no return value*/) {

// script.js has been loaded.

});
Optimize!

But aren't that too many HTTP requests?
| Loading is very efficient
     ●   Great for development
     ●   Useful for a few or external resources
| For production you need to make a build
     ●   One big file or multiple layers
     ●   Command line tools to resolve dependencies at build time (not run time)
     ●   Inline text resources like template files
     ●   Optimize (e.g. Closure Compiler)
AMD

| Predecessors:
      ●   Dojo: dojo.require("some.module") (resp. goog.require)
      ●   LABjs: $LAB.script("some/module.js")
      ●   CommonJS: require("some/module")
| Current support
      ●   jQuery 1.7
      ●   Dojo 1.7
      ●   MooTools 2.0
      ●   EmbedJS
      ●   Backbone/underscore will
Tools

| RequireJS
        ●   Loader
        ●   Optimizer (r.js)

| curl.js
| ...
| Dojo 1.7 provides own AMD loader and build tool.
Resources

| requirejs.org
     ●   Great docs about AMD in general, too
| github.com/amdjs
     ●   Official spec in the wiki
| Google group amd-implement
| commonjs.org
     ●   General information but not home of AMD any more
Conclusion

| Should I use it?
| How mature?
| Will it stay?
danke!
Martin Stadler

 | Email: martin@siarp.de
 | Twitter: @xMartin




excentos GmbH
www.excentos.com

More Related Content

What's hot

Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewVisual Engineering
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존동수 장
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orgAgelos Pikoulas
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJohan Nilsson
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development toolsSimon Kim
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Managing JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSManaging JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSDen Odell
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JSJacob Nelson
 
Nodejs getting started
Nodejs getting startedNodejs getting started
Nodejs getting startedTriet Ho
 
Requirejs
RequirejsRequirejs
Requirejssioked
 

What's hot (20)

Express node js
Express node jsExpress node js
Express node js
 
Workshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General OverviewWorkshop Intro: FrontEnd General Overview
Workshop Intro: FrontEnd General Overview
 
RequireJS
RequireJSRequireJS
RequireJS
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Node ppt
Node pptNode ppt
Node ppt
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
ngCore
ngCorengCore
ngCore
 
Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.org
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Requirejs
RequirejsRequirejs
Requirejs
 
Managing JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSManaging JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJS
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
D2
D2D2
D2
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
 
Nodejs getting started
Nodejs getting startedNodejs getting started
Nodejs getting started
 
Requirejs
RequirejsRequirejs
Requirejs
 

Similar to Asynchronous Module Definition (AMD)

Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
Es6 modules-and-bundlers
Es6 modules-and-bundlersEs6 modules-and-bundlers
Es6 modules-and-bundlersismnoiet
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbaiCIBIL
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS InternalEyal Vardi
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic ComponentsMateusz Tymek
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Titanium appcelerator best practices
Titanium appcelerator best practicesTitanium appcelerator best practices
Titanium appcelerator best practicesAlessio Ricco
 

Similar to Asynchronous Module Definition (AMD) (20)

Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
Android - Anatomy of android elements & layouts
Android - Anatomy of android elements & layoutsAndroid - Anatomy of android elements & layouts
Android - Anatomy of android elements & layouts
 
Es6 modules-and-bundlers
Es6 modules-and-bundlersEs6 modules-and-bundlers
Es6 modules-and-bundlers
 
Android training in mumbai
Android training in mumbaiAndroid training in mumbai
Android training in mumbai
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Zend Framework 2 - Basic Components
Zend Framework 2  - Basic ComponentsZend Framework 2  - Basic Components
Zend Framework 2 - Basic Components
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Titanium appcelerator best practices
Titanium appcelerator best practicesTitanium appcelerator best practices
Titanium appcelerator best practices
 

Recently uploaded

UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 

Recently uploaded (20)

UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 

Asynchronous Module Definition (AMD)

  • 1. Asynchronous Module Definition (AMD) The missing client-side JavaScript module system.
  • 2. about me Martin Stadler | Frontend engineer / JavaScript developer @ excentos | Web developer since 2004 (HTML/CSS, PHP, Python, Drupal, Plone, jQuery, …) | Developing modular single-page apps since 01/2010 | Email: martin@siarp.de | Twitter: @xMartin
  • 3. excentos – what we do Product Advisors | Web apps to find the right product for you | Goal: to perform like a human sales expert | Single-page JavaScript, Dojo Toolkit
  • 4. Overview Asynchronous Module Definition (AMD) | Motivation | Modules | Loading | Optimization | Conclusion | Questions/Discussion
  • 5. Motivation | Pages turn into apps ● More code ● More complex ● Serious development, not just a few lines of script | Design principles ● Separate into reusable components ● Avoid global namespace pollution
  • 6. What is a Module? Manual dependency resolution <head> <script src="myLib.js"></script> <script src="myLibPlugin.js"></script> <script src="mySpaghettiCode.js"></script> </head>
  • 7. What is a Module? JavaScript module pattern var mymodule = (function() { var a = 'x', doSth = function(){...}; return { getA: function() { return doSth(a); } }; })(); Where does it live? | Global? At least reusable. | Closure? Closure of what?
  • 8. What is a Module? | module = resource | declares dependencies Python mymodule.py app.py $ python app.py def printSth(): import mymodule sth print 'sth' mymodule.printSth() NodeJS mymodule.js app.js $ node app.js exports.printSth = var mymodule = sth function() { require('./mymodule'); console.log('sth'); }; mymodule.printSth();
  • 9. What is a Module? AMD mymodule.js app.js index.html define(function() { define([ <script "mymodule" src="loader.js"></script> return { ], function(myMod) { <script> printSth: function() { require( alert("sth"); myMod.printSth(); ["app"], }; function(app) { }); // if app returned }); // something, we'd use // it here... }); </script>
  • 10. AMD | Asynchronous ● Don't block browser ● Parallel download and interpretation ● Callbacks everywhere... | Loaded via script tag injection (not XHR + eval) ● Debugging ● X-Domain
  • 11. Loader Plugins define([ "../Widget", "text!./tpl.html" ], function(Widget, tpl) { return new Widget({name: "mainApp", template: tpl}) }); | text! ● Load via XHR ● E.g. templates for widgets, data
  • 12. Load non-modules require([ "dir/foo.js", "http://host/script.js" ], function(/*no return value*/) { // script.js has been loaded. });
  • 13. Optimize! But aren't that too many HTTP requests? | Loading is very efficient ● Great for development ● Useful for a few or external resources | For production you need to make a build ● One big file or multiple layers ● Command line tools to resolve dependencies at build time (not run time) ● Inline text resources like template files ● Optimize (e.g. Closure Compiler)
  • 14. AMD | Predecessors: ● Dojo: dojo.require("some.module") (resp. goog.require) ● LABjs: $LAB.script("some/module.js") ● CommonJS: require("some/module") | Current support ● jQuery 1.7 ● Dojo 1.7 ● MooTools 2.0 ● EmbedJS ● Backbone/underscore will
  • 15. Tools | RequireJS ● Loader ● Optimizer (r.js) | curl.js | ... | Dojo 1.7 provides own AMD loader and build tool.
  • 16. Resources | requirejs.org ● Great docs about AMD in general, too | github.com/amdjs ● Official spec in the wiki | Google group amd-implement | commonjs.org ● General information but not home of AMD any more
  • 17. Conclusion | Should I use it? | How mature? | Will it stay?
  • 18. danke! Martin Stadler | Email: martin@siarp.de | Twitter: @xMartin excentos GmbH www.excentos.com