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

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

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