SlideShare a Scribd company logo
RequireJSAdventures with an asynchronous script loaderSome content borrowed from http://www.tagneto.org/talks/jQueryRequireJS/jQueryRequireJS.pdf and http://requirejs.orgTim Doherty
TemplatesYour own sub headlineThe Problem
Script Tag Vomit
Solution
AMD
RequireJS
ConclusionWeb sites are turning into Web appsCode complexity grows as the site gets biggerAssembly gets harderDeveloper wants discrete JS files/modulesDeployment wants optimized code in just one or a few HTTP callsThe Problem
Script Tag Vomit<script src=“http://localhost/AppSite/Scripts/ThirdParty/require.js type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/main.js” type=“text/javascript”></script><script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/controller.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/model.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/view.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/config.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Utilities/utils.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Experian/experian.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/email.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/log.js" type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Utilities/countdownTimer.js" type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/ThirdParty/jquery.validity.pack-wrapped.js” type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/ThirdParty/json2.js” type=“text/javascript”></script><script src=“” http://localhost/myCompany.core.javascript/Scripts/Core/states.js type=“text/javascript”></script>http://www.flickr.com/photos/nicasaurusrex/1363221060/
SlowMany HTTP RequestsBlocking renderManual DependeciesLacks EncapsulationScript Tag Vomithttp://www.flickr.com/photos/nicasaurusrex/1363221060/
Front-end developers need a solution with:Some sort of #include/import/requireAbility to load nested dependencies asynchronouslyEase of use for developer backed by an optimization tool that helps deploymentSolution
AMDAsynchronous Module DefinitionAMD attempts to address the following problem:    Ability to load nested dependenciesasynchronouslyFrom https://github.com/amdjs/amdjs-api/wiki/AMD:The Asynchronous Module Definition API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loadedThe specification defines a single function "define" that is available as a free variable or a global variable:	define(id?, dependencies?, factory);AMD is a specification, not a technologyAMD is the basis for a number of script loader libraries…
AMDImplementationsRequireJS
Nodules
JSLocalnet
Curl.jsRequireJS implements AMD to solve these additional problems:Some sort of #include/import/requireEase of use for developer backed by an optimization tool that helps deploymentRequireJS
RequireJShttp://requirejs.org:RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.    Asynchronous script loader
    Call it anytime
    Encapsulation
    Trace nested dependencies
    Avoid polluting the global namespace
    Optimization tool for JS/CSSRequireJSrequire()Simplest use-case, load a single JS file:require([“scripts/myScript.js”], function () {//Do something once the script has loaded});
RequireJSrequire()require() can load an array of AMD modules as dependencies: require(        [	// array of dependencies            “dependency1“,            “dependency2”         ],function (dependency1, dependency2) {            // use dependencies            dependency1.someMethod();…etc…        });More on that later…
<script src=“require.js” type=“text/javascript></script><script type=“text/javascript>	require([		“Application/controller”,		“Application/model”,		“Application/view”,		“config”,		“Core/Utilities/utils”,		“Core/Experian/experian”,		“Core/Experian/email”		“Core/Experian/log”		“Core/Utilities/countdownTimer”,		…etc…	])</script>RequireJSBetter Vomit
<script src=“require.js” data-main=“main” type=“text/javascript></script>More on that later…RequireJSBest
RequireJS creates script tags on demand and adds them to the head:var head = document.getElementsByTagName('head')[0],    script = document.createElement('script');script.src = url;head.appendChild(script);This approach has the following advantages:Will not block page rendering Works after page loadNot constrained by same origin policy (SOP)RequireJSLoading Scripts
RequireJSLoading ScriptsHowever, we need to know the dependencies and make sure we load them before executing our script. The best way to do that is to use function wrappers. We pass function wrappers to the define() method, to create RequireJS modules: define(//The name of this module    “module1",//The array of dependencies    [“dependency1"], //filename without “.js” indicates a module//The function to execute when all dependencies have loaded. The arguments    //to this function are the array of dependencies mentioned above.function (dependency1) {return {		method1: function() {//Use the dependency			dependency1.someMethod();		}	};    });
RequireJSJavaScript Module Pattern(function () { //Do setup work herereturn { 		color: "black", 		size: "unisize" 	} })();
RequireJSRequireJS Module Patterndefine(function () { //Do setup work herereturn { 		color: "black", 		size: "unisize" 	} });
RequireJSRequireJS Module PatternThe RequireJS syntax for modules allows them to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order, and since global variables are not created, it makes it possible to load multiple versions of a module in a pageExtension of the widely used JS module patternMinimal boilerplate code for developers to adoptDefines a well-scoped object that avoids polluting the global namespaceExplicitly lists its dependenciesReceives dependencies as arguments to the function that defines the moduleDoes not need globals to refer to other modules
RequireJSModule Pattern Benefits    Encapsulation
    Dependency management
    Programming against interfaces vs. implementations
    Single responsibility principle
    Reduced file size
    ReusabilityRequireJSdefine()Simplest use-case - name/value pairs with no dependencies:shirt.js://pass an object literal to define()define({    color: “black”,    size: “unisize”});To use this simple module:require([“shirt”], function (shirt) {//Do something once shirt.js has loaded    console.log(“Color: “ + shirt.color);    console.log(“Size: “ + shirt.size);});
RequireJSdefine()Definition functions - use a function to do setup work then define the module:shirt.js://pass a function that does setup work //before returning a module definition. define(function () { //Do setup work here     //return an object to define the modulereturn {         color: "black",         size: "unisize"     } });
RequireJSdefine()Definition functions with dependencies - use dependencies and a function with dependency arguments to do setup work then define the module:shirt.js://pass an array of dependencies, and a function that//does setup work before returning a module definition. define(["./cart", "./inventory"] ,function (cart, inventory) { //Do setup work here      //return an object to define the modulereturn {         color: "black",         size: "unisize“,addToCart: function() {//use the dependencies in the module definitioninventory.decrement(this); cart.add(this);         }     } });
RequireJSModule Naming SchemeModule names are mapped to directory/file structure* allowing intuitive organization of source files:Assuming a base path of “Scripts” the module naming scheme for these modules would be:“Application/controller”
“Application/model”
“Application/view”* This can be changed via the “paths” config, see RequireJS documentation for details
RequireJSDependency ManagementModules can specify their dependencies explicitly:Dependencies can be nestedLoad once, use in multiple locationsPlugins for text dependencies, load order, etc.Compatible with JavaScript prototypal inheritance
RequireJSPrototypal InheritanceInject prototypes as dependencies and return constructor functions from our modules to create new objectsdefine(//The name of this module    "types/Manager",//The array of dependencies    ["types/Employee"],//The function to execute when all dependencies have loaded. The arguments    //to this function are the array of dependencies mentioned above.function (Employee) {function Manager () {this.reports = [];        }        //This will now workManager.prototype = new Employee();        //return the Manager constructor function so it can be used by other modules.return Manager;    });
RequireJSObject CompositionExpose dependencies in a module’s return value to create new objects by compositiondefine(//The array of dependencies    [“dependency1"],    [“dependency2"]//The function to execute when all dependencies have loaded. The arguments    //to this function are the array of dependencies mentioned above.function (dependency1, dependency2) {        //do setup work        //expose dependencies as properties of returned object return {//module-defined code	…	composedMethod1: dependency1.someMethod,	composedObject2: dependency2,        };    });

More Related Content

PPT
Managing JavaScript Dependencies With RequireJS
PPTX
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
PDF
Requirejs
KEY
Requirejs
PDF
Modularize JavaScript with RequireJS
PPTX
Require js
PDF
JavaScript Dependencies, Modules & Browserify
PDF
Browserify
Managing JavaScript Dependencies With RequireJS
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Requirejs
Requirejs
Modularize JavaScript with RequireJS
Require js
JavaScript Dependencies, Modules & Browserify
Browserify

What's hot (20)

PDF
Lightning Talk: Making JS better with Browserify
PPTX
Introduction to require js
PDF
Javascript ui for rest services
PPT
Require JS
PPTX
AngularJS - Architecture decisions in a large project 
PPT
JavaScript Modules in Practice
PDF
AngularJS 101 - Everything you need to know to get started
PDF
Asynchronous Module Definition (AMD)
PDF
Frontend Application Architecture, Patterns, and Workflows
PPTX
uRequire@greecejs: An introduction to http://uRequire.org
PDF
AngularJS with RequireJS
PPTX
Workshop Intro: FrontEnd General Overview
PDF
Modern Web Application Development Workflow - EclipseCon Europe 2014
PPTX
Javascript Bundling and modularization
PDF
An Introduction To Testing In AngularJS Applications
PDF
Module, AMD, RequireJS
PDF
Workshop 2: JavaScript Design Patterns
PDF
Angularjs architecture
PDF
Design & Development of Web Applications using SpringMVC
KEY
CommonJS Everywhere (Wakanday 2011)
Lightning Talk: Making JS better with Browserify
Introduction to require js
Javascript ui for rest services
Require JS
AngularJS - Architecture decisions in a large project 
JavaScript Modules in Practice
AngularJS 101 - Everything you need to know to get started
Asynchronous Module Definition (AMD)
Frontend Application Architecture, Patterns, and Workflows
uRequire@greecejs: An introduction to http://uRequire.org
AngularJS with RequireJS
Workshop Intro: FrontEnd General Overview
Modern Web Application Development Workflow - EclipseCon Europe 2014
Javascript Bundling and modularization
An Introduction To Testing In AngularJS Applications
Module, AMD, RequireJS
Workshop 2: JavaScript Design Patterns
Angularjs architecture
Design & Development of Web Applications using SpringMVC
CommonJS Everywhere (Wakanday 2011)
Ad

Viewers also liked (20)

PDF
Introduction to Backbone.js
PPTX
Backbone And Marionette : Take Over The World
PDF
Introduction à Marionette
PDF
Introduction to Backbone.js
PDF
AngularJS vs. Ember.js vs. Backbone.js
PPT
Backbone.js
PDF
Intro to Backbone.js by Azat Mardanov for General Assembly
KEY
Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ...
PPTX
MVC & backbone.js
PPTX
Backbone/Marionette recap [2015]
PDF
Introduction to Marionette Collective
PPTX
Introduction to Backbone.js & Marionette.js
PPTX
Marionette talk 2016
PDF
Client-side MVC with Backbone.js
PDF
introduction to Marionette.js (jscafe14)
PDF
Marionette: the Backbone framework
PPTX
Backbone.js
PDF
PPTX
Introduction to Backbone.js
PDF
Pdf 2 t12 en
Introduction to Backbone.js
Backbone And Marionette : Take Over The World
Introduction à Marionette
Introduction to Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
Backbone.js
Intro to Backbone.js by Azat Mardanov for General Assembly
Beautiful Maintainable ModularJavascript Codebase with RequireJS - HelsinkiJ...
MVC & backbone.js
Backbone/Marionette recap [2015]
Introduction to Marionette Collective
Introduction to Backbone.js & Marionette.js
Marionette talk 2016
Client-side MVC with Backbone.js
introduction to Marionette.js (jscafe14)
Marionette: the Backbone framework
Backbone.js
Introduction to Backbone.js
Pdf 2 t12 en
Ad

Similar to RequireJS (20)

PDF
IOC + Javascript
PPTX
Packing for the Web with Webpack
PDF
Warsaw Frontend Meetup #1 - Webpack
ODP
Exploring Symfony's Code
PPTX
node.js.pptx
PDF
Web Components v1
PPTX
Rails Engine | Modular application
PDF
Create an application with ember
PDF
Dependency Management with RequireJS
KEY
Modules and EmbedJS
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
PDF
Voorhoede - Front-end architecture
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
PDF
Styling components with JavaScript
PDF
Build Web Apps using Node.js
PDF
Full Stack React Workshop [CSSC x GDSC]
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
PDF
Social Connections VI — IBM Connections Extensions and Themes Demystified
PDF
Handlebars & Require JS
IOC + Javascript
Packing for the Web with Webpack
Warsaw Frontend Meetup #1 - Webpack
Exploring Symfony's Code
node.js.pptx
Web Components v1
Rails Engine | Modular application
Create an application with ember
Dependency Management with RequireJS
Modules and EmbedJS
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Voorhoede - Front-end architecture
Writing HTML5 Web Apps using Backbone.js and GAE
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Styling components with JavaScript
Build Web Apps using Node.js
Full Stack React Workshop [CSSC x GDSC]
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Social Connections VI — IBM Connections Extensions and Themes Demystified
Handlebars & Require JS

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Approach and Philosophy of On baking technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Network Security Unit 5.pdf for BCA BBA.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
A Presentation on Artificial Intelligence
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
The AUB Centre for AI in Media Proposal.docx
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Diabetes mellitus diagnosis method based random forest with bat algorithm
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
Approach and Philosophy of On baking technology
Digital-Transformation-Roadmap-for-Companies.pptx

RequireJS

  • 1. RequireJSAdventures with an asynchronous script loaderSome content borrowed from http://www.tagneto.org/talks/jQueryRequireJS/jQueryRequireJS.pdf and http://requirejs.orgTim Doherty
  • 2. TemplatesYour own sub headlineThe Problem
  • 5. AMD
  • 7. ConclusionWeb sites are turning into Web appsCode complexity grows as the site gets biggerAssembly gets harderDeveloper wants discrete JS files/modulesDeployment wants optimized code in just one or a few HTTP callsThe Problem
  • 8. Script Tag Vomit<script src=“http://localhost/AppSite/Scripts/ThirdParty/require.js type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/main.js” type=“text/javascript”></script><script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/controller.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/model.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/Application/view.js " type=“text/javascript”></script><script src=“http://localhost/AppSite/Scripts/config.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Utilities/utils.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Experian/experian.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/email.js " type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/log.js" type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/Core/Utilities/countdownTimer.js" type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/ThirdParty/jquery.validity.pack-wrapped.js” type=“text/javascript”></script><script src=“http://localhost/myCompany.core.javascript/Scripts/ThirdParty/json2.js” type=“text/javascript”></script><script src=“” http://localhost/myCompany.core.javascript/Scripts/Core/states.js type=“text/javascript”></script>http://www.flickr.com/photos/nicasaurusrex/1363221060/
  • 9. SlowMany HTTP RequestsBlocking renderManual DependeciesLacks EncapsulationScript Tag Vomithttp://www.flickr.com/photos/nicasaurusrex/1363221060/
  • 10. Front-end developers need a solution with:Some sort of #include/import/requireAbility to load nested dependencies asynchronouslyEase of use for developer backed by an optimization tool that helps deploymentSolution
  • 11. AMDAsynchronous Module DefinitionAMD attempts to address the following problem: Ability to load nested dependenciesasynchronouslyFrom https://github.com/amdjs/amdjs-api/wiki/AMD:The Asynchronous Module Definition API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loadedThe specification defines a single function "define" that is available as a free variable or a global variable: define(id?, dependencies?, factory);AMD is a specification, not a technologyAMD is the basis for a number of script loader libraries…
  • 15. Curl.jsRequireJS implements AMD to solve these additional problems:Some sort of #include/import/requireEase of use for developer backed by an optimization tool that helps deploymentRequireJS
  • 16. RequireJShttp://requirejs.org:RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code. Asynchronous script loader
  • 17. Call it anytime
  • 18. Encapsulation
  • 19. Trace nested dependencies
  • 20. Avoid polluting the global namespace
  • 21. Optimization tool for JS/CSSRequireJSrequire()Simplest use-case, load a single JS file:require([“scripts/myScript.js”], function () {//Do something once the script has loaded});
  • 22. RequireJSrequire()require() can load an array of AMD modules as dependencies: require( [ // array of dependencies “dependency1“, “dependency2” ],function (dependency1, dependency2) { // use dependencies dependency1.someMethod();…etc… });More on that later…
  • 23. <script src=“require.js” type=“text/javascript></script><script type=“text/javascript> require([ “Application/controller”, “Application/model”, “Application/view”, “config”, “Core/Utilities/utils”, “Core/Experian/experian”, “Core/Experian/email” “Core/Experian/log” “Core/Utilities/countdownTimer”, …etc… ])</script>RequireJSBetter Vomit
  • 24. <script src=“require.js” data-main=“main” type=“text/javascript></script>More on that later…RequireJSBest
  • 25. RequireJS creates script tags on demand and adds them to the head:var head = document.getElementsByTagName('head')[0], script = document.createElement('script');script.src = url;head.appendChild(script);This approach has the following advantages:Will not block page rendering Works after page loadNot constrained by same origin policy (SOP)RequireJSLoading Scripts
  • 26. RequireJSLoading ScriptsHowever, we need to know the dependencies and make sure we load them before executing our script. The best way to do that is to use function wrappers. We pass function wrappers to the define() method, to create RequireJS modules: define(//The name of this module “module1",//The array of dependencies [“dependency1"], //filename without “.js” indicates a module//The function to execute when all dependencies have loaded. The arguments //to this function are the array of dependencies mentioned above.function (dependency1) {return { method1: function() {//Use the dependency dependency1.someMethod(); } }; });
  • 27. RequireJSJavaScript Module Pattern(function () { //Do setup work herereturn { color: "black", size: "unisize" } })();
  • 28. RequireJSRequireJS Module Patterndefine(function () { //Do setup work herereturn { color: "black", size: "unisize" } });
  • 29. RequireJSRequireJS Module PatternThe RequireJS syntax for modules allows them to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order, and since global variables are not created, it makes it possible to load multiple versions of a module in a pageExtension of the widely used JS module patternMinimal boilerplate code for developers to adoptDefines a well-scoped object that avoids polluting the global namespaceExplicitly lists its dependenciesReceives dependencies as arguments to the function that defines the moduleDoes not need globals to refer to other modules
  • 31. Dependency management
  • 32. Programming against interfaces vs. implementations
  • 33. Single responsibility principle
  • 34. Reduced file size
  • 35. ReusabilityRequireJSdefine()Simplest use-case - name/value pairs with no dependencies:shirt.js://pass an object literal to define()define({ color: “black”, size: “unisize”});To use this simple module:require([“shirt”], function (shirt) {//Do something once shirt.js has loaded console.log(“Color: “ + shirt.color); console.log(“Size: “ + shirt.size);});
  • 36. RequireJSdefine()Definition functions - use a function to do setup work then define the module:shirt.js://pass a function that does setup work //before returning a module definition. define(function () { //Do setup work here //return an object to define the modulereturn { color: "black", size: "unisize" } });
  • 37. RequireJSdefine()Definition functions with dependencies - use dependencies and a function with dependency arguments to do setup work then define the module:shirt.js://pass an array of dependencies, and a function that//does setup work before returning a module definition. define(["./cart", "./inventory"] ,function (cart, inventory) { //Do setup work here //return an object to define the modulereturn { color: "black", size: "unisize“,addToCart: function() {//use the dependencies in the module definitioninventory.decrement(this); cart.add(this); } } });
  • 38. RequireJSModule Naming SchemeModule names are mapped to directory/file structure* allowing intuitive organization of source files:Assuming a base path of “Scripts” the module naming scheme for these modules would be:“Application/controller”
  • 40. “Application/view”* This can be changed via the “paths” config, see RequireJS documentation for details
  • 41. RequireJSDependency ManagementModules can specify their dependencies explicitly:Dependencies can be nestedLoad once, use in multiple locationsPlugins for text dependencies, load order, etc.Compatible with JavaScript prototypal inheritance
  • 42. RequireJSPrototypal InheritanceInject prototypes as dependencies and return constructor functions from our modules to create new objectsdefine(//The name of this module "types/Manager",//The array of dependencies ["types/Employee"],//The function to execute when all dependencies have loaded. The arguments //to this function are the array of dependencies mentioned above.function (Employee) {function Manager () {this.reports = []; } //This will now workManager.prototype = new Employee(); //return the Manager constructor function so it can be used by other modules.return Manager; });
  • 43. RequireJSObject CompositionExpose dependencies in a module’s return value to create new objects by compositiondefine(//The array of dependencies [“dependency1"], [“dependency2"]//The function to execute when all dependencies have loaded. The arguments //to this function are the array of dependencies mentioned above.function (dependency1, dependency2) { //do setup work //expose dependencies as properties of returned object return {//module-defined code … composedMethod1: dependency1.someMethod, composedObject2: dependency2, }; });
  • 44. RequireJSText DependenciesIt is nice to build HTML using regular HTML tags, instead of building up DOM structures in script. However, there is no good way to embed HTML in a JavaScript file. RequireJS has a plugin, text.js, that can help with this issue.require(["some/module", "text!some/module.html", "text!some/module.css"], function(module, html, css) { //the html variable will be the text //of the some/module.html file //the css variable will be the text //of the some/module.css file. } );At build time, the optimizer will inline these text dependencies in the resulting optimized file for deployment.
  • 45. RequireJSPage Load SupportThe require.ready() method allows a callback when the DOM is ready AND all dependencies have been loaded:require(["module/one", "module/two"],function(one, two) { require.ready(function() { //DOM is ready AND all dependencies loadedone.modifyTheDom(); }); } );This is similar to the document.ready() method in jQuery.However, since it also ensures that all dependencies are loaded, require.ready() should be used in place of jQuery’sdocument.ready in any project using both jQuery and RequireJS.
  • 46. While you can use require() inside a script tag in an HTML file, it is strongly encouraged to place the work in a file that is loaded by RequireJS. This allows for easier optimization via the optimization tool, and there is a shorthand that can be used in the HTML for this pattern:<script src=“require.js” data-main=“main” type=“text/javascript></script>Main.js:require([“scripts/myScript.js”], function () {//Do something once the script has loaded});The data-main attribute tells RequireJS to take the value of the data-main attribute and treat it like a require([]) callRequireJSData-main
  • 47. RequireJS includes an optimization tool to help deploymentCombine modules into fewer files for deploymentIn some cases, this could be a single file!Java & node versionsConcatenate & minify JS filesShallow file exclusion for tweaking/debugging individual JS filesConcatenate CSS @import filesMinify CSS filesFile system vs. URLsRequireJSOptimizer
  • 48. Build File:({appDir: "../", //main application directorybaseUrl: "Scripts", //path, relative to “dir”, where RequireJS should start looking for modules dir: "../../Build", //build output directory paths: { //optional path aliases "jQuery": "empty", "convert": "conversionFunctions", }, optimize: "uglify", //"uglify", "closure" (Java Only), "closure.keepLines" (Java Only), "none" modules: [ //array of modules to optimize { name: "main", exclude: ["jQuery", "config"] //exclude these dependencies from the optimized “main.js” file } ]})RequireJSOptimizer
  • 50. For multi-page applications, layered optimization may make sense:Layer(s) for common application code, including 3rd-party librariesLayer for page-specific scriptsRequireJSOptimizer – Layers
  • 51. Common code:appCommon.js:define( [ "../../Scripts/commonFunctions", "../../Scripts/form-utils“, "../../Scripts/jquery-1.4.1.min.js", "order!../../Scripts/datepicker.js", "order!../../Scripts/jquery.validate.min.js“, …etc… ],function (commonFunctions, form-utils) {//create common code module definition });RequireJSOptimizer – Layers
  • 52. Page 1 module:page1.js:require(["appCommon"], function() { //code specific to page 1 });RequireJSOptimizer – Layers
  • 53. Page 2 module:page2.js:require(["appCommon"], function() { //code specific to page 2 });RequireJSOptimizer – Layers
  • 54. Build file:app.build.js:({//config options excluded for brevity… modules: [ { name: "appCommon“ //optimize appCommon by itself }, { name: “page1", exclude: ["appCommon"] //exclude appCommon from optimized “page1.js” file }, { name: “page2", exclude: ["appCommon"] //exclude appCommon from optimized “page2.js” file } ]})RequireJSOptimizer – Layers
  • 55. The build output will be:Optimized appCommon.js fileOptimized page1.js file with optimized appCommon.js as a dependencyOptimized page2.js file with optimized appCommon.js as a dependencyRequireJSOptimizer – Layers
  • 56. Development– use a local website hosting the shared code:paths: { "ThirdParty": “http://localhost/myCompany.Core.Javascript/Scripts/ThirdParty", "core": "http://localhost/myCompany.Core.Javascript/Scripts/Core", "text": "http://localhost/myCompany.Core.Javascript/Scripts/ThirdParty/text", "order": "http://localhost/myCompany.Core.Javascript/Scripts/ThirdParty/order“},Build – pull shared code from corresponding file paths:paths: { "ThirdParty": "../../../myCompany.Core/myCompany.Core.Javascript/Scripts/ThirdParty", "core": "../../../myCompany.Core/myCompany.Core.Javascript/Scripts/Core", "text": "../../../myCompany.Core/myCompany.Core.Javascript/Scripts/ThirdParty/text", "order": "../../../myCompany.Core/myCompany.Core.Javascript/Scripts/ThirdParty/order“},During development, modules are loaded async from a single, version-controlled projectDuring build, modules are copied from the file system and combined into a single file to be deployed with the target projectRequireJSOptimizer - Shared Code
  • 57. RequireJSOptimizer - Shared Code - DevelopmentApp SiteMain.jsFile SystemShared CodeShared Code Site
  • 58. RequireJSOptimizer - Shared Code - BuildMain.jsMain.js - optimizedFile SystemShared CodeOptimizer
  • 59. RequireJSOptimizer - Shared Code - DeploymentMain.jsApp SiteFile System
  • 60. RequireJSOptimizer – Visual Studio IntegrationAdd build commands to post-build events:
  • 61. RequireJSHello WorldHello World sample applicationhello.js: defines an object with a single property “text” = “Hello”world.js: defines an object with a single property “text” = “World!”main.js: require’s “hello” and “world” and outputs “text” propertiesindex.html: script tag for require.js with data-main attribute for main.jsapp.build.js: build filehttp://www.flickr.com/photos/oskay/472097903/
  • 64. RequireJSHello Worldmain.js:require( ["hello", "world"],function(hello, world){ alert(hello.text + " " + world.text); });
  • 65. RequireJSHello Worldindex.html:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title></title> </head> <body> <script src="scripts/require.js" data-main="scripts/main" type="text/javascript"></script> </body></html>
  • 67. RequireJSHello World - DevelopmentScript tags inserted into the head on-demand:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title></title> <script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="main" src="scripts/main.js"> <script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="hello" src="scripts/hello.js"> <script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="world" src="scripts/world.js"> </head> <body> <script type="text/javascript" data-main="scripts/main" src="scripts/require.js"> </body></html>
  • 68. RequireJSHello World - Buildapp.build.js:({appDir: "../",baseUrl: "scripts", dir: "../Build", paths: {}, optimize: "uglify", modules: [ { name: "main“ } ]})
  • 69. RequireJSHello World - BuildBuild: (Win32 command prompt with Node)C:\> C:\>cd <projectpath>\scriptsC:\<projectpath>\scripts>C:\<projectpath>\scripts>node <requirejspath>\r.js -o app.build.js
  • 70. RequireJSHello World - Build<projectpath>\Build\scripts\main.js:define(“hello",{text:"Hello"}),define(“world",{text:"World!"}),require([“hello",“world"],function(a,b){alert(a.text+" "+b.text)}),define("main",function(){})
  • 72. Stop vomiting script tags!AMD is gaining tractionAMD brings sanity to JavaScript developmentStructure, encapsulation, dependency management Write once, use anywhereRequireJS is the most popular AMD script loaderRequireJS likely to be part of Dojo 2.0RequireJS nearing 1.0 releaseOpen source, active communityConclusion
  • 73. RequireJSAdventures with an asynchronous script loaderhttp://requirejs.orghttps://github.com/jrburke/r.jshttp://tagneto.blogspot.com/https://github.com/amdjs/amdjs-api/wiki/AMD http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depthhttp://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/RequireJS is an open source project authored by James Burke, open source developer, RequireJS, Mozilla Messaging, and Dojo.