SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
DEPENDENCY	
  	
  
MANAGEMENT	
  
with	
  RequireJS	
  
HELLO	
  
                              my	
  name	
  is	
  


         Aaron Hardy
                                    ·∙	
  
                   @AARONIUS	
  	
  	
  	
  	
  AARONHARDY.COM	
  


So8ware	
  Engineer,	
  Adobe	
  Digital	
  MarkeAng	
  Suite	
  
     We	
  enable	
  management,	
  measurement,	
  execu1on,	
  and	
  
       op1miza1on	
  of	
  digital	
  adver1sing	
  and	
  marke1ng.	
  
What	
  is	
  dependency	
  management?	
  
Loading…	
  
The	
  right	
  code.	
  
In	
  the	
  right	
  order.	
  
At	
  the	
  right	
  Ame.	
  
At	
  the	
  right	
  speed.	
  
	
  
(oh	
  and	
  btw,	
  make	
  it	
  easy)	
  
	
  
	
  
Old-­‐school	
  Dependency	
  Management	
  
What	
  are	
  the	
  dependencies	
  here?	
  
<script     src="script3.js"></script>
<script     src="script1.js"></script>
<script     src="script13.js"></script>
<script     src="script7.js"></script>
<script     src="script6.js"></script>
<script     src="script12.js"></script>
<script     src="script4.js"></script>
<script     src="script11.js"></script>
<script     src="script5.js"></script>
<script     src="script9.js"></script>
<script     src="script8.js"></script>
<script     src="script10.js"></script>
<script     src="script2.js"></script>
Old-­‐school	
  Dependency	
  Management	
  
What	
  is	
  a	
  module?	
  
A	
  structure	
  used	
  to	
  encapsulate	
  methods	
  and	
  aTributes	
  to	
  avoid	
  
polluAng	
  the	
  global	
  namespace.	
  
var Calculator = (function(){
  function funkify(num) {
    return num * Math.random() / Math.random();
  }

   function add(a, b, getFunky){
     var sum = a + b;
     return getFunky ? funkify(sum) : sum;
   }

  return {
     add:add
  };
})();
What	
  is	
  AMD?	
  
Asynchronous	
  module	
  definiAon.	
  	
  	
  
•  A	
  mechanism	
  for	
  defining	
  modules	
  such	
  that	
  the	
  module	
  and	
  its	
  
   dependencies	
  can	
  be	
  asynchronously	
  loaded.	
  
•  Suited	
  for	
  a	
  browser	
  environment.	
  
•  Generally	
  used	
  in	
  tandem	
  with	
  an	
  AMD	
  loader.	
  
What	
  is	
  RequireJS?	
  
A	
  JavaScript	
  file	
  and	
  module	
  loader.	
  Capable	
  of	
  loading	
  modules	
  
defined	
  in	
  the	
  AMD	
  format	
  and	
  their	
  dependencies.	
  
	
  
Not	
  the	
  only	
  AMD	
  loader	
  (but	
  unofficially	
  the	
  most	
  popular)	
  
•  curl.js	
  
•  lsjs	
  
•  dojo	
  
•  mootools	
  
	
  
Open	
  source.	
  New	
  BSD	
  or	
  MIT	
  licensed.	
  
Defining	
  a	
  module 	
  	
  
/js/book.js	
  
define({
  title: "My Sister's Keeper",
  publisher: "Atria"
});
RequesAng	
  dependencies	
  
/js/bookshelf.js	
  
define([
  'book'
], function(book) {
  return {
     listBook: function() {
       alert(book.title);
     }
  };
});
Se]ng	
  up	
  your	
  app	
  
/index.html	
  
<!DOCTYPE html>
<html>
  <head>
    <title>RequireJS Example</title>
    <script data-main="js/main"
         src="js/libs/require.js"></script>
  </head>
  <body/>
</html>
Se]ng	
  up	
  your	
  app	
  
/js/main.js	
  
require([
  'bookshelf'
], function(bookshelf) {
  bookshelf.listBook();
});
define()	
  vs.	
  require()	
  
define()	
  completes	
  three	
  steps:	
  
1.  Loads	
  the	
  specified	
  dependencies	
  
2.  Calls	
  the	
  callback	
  funcAon	
  
3.  Registers	
  the	
  return	
  value	
  from	
  the	
  callback	
  funcAon	
  

require()	
  only	
  performs	
  #1	
  and	
  #2.	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐literal	
  
Defining	
  a	
  constructor	
  module 	
  	
  
/js/book.js	
  
define(function() {
  var Book = function(title, publisher) {
     this.title = title;
     this.publisher = publisher;
  };
  return Book;
});
Using	
  a	
  constructor	
  module 	
  	
  
/js/bookshelf.js	
  
define([
  'book'
], function(Book) {
  var books = [
     new Book('A Tale of Two Cities', 'Chapman & Hall'),
     new Book('The Good Earth', 'John Day')
  ];

  return {
     listBooks: function() {
       for (var i = 0, ii = books.length; i < ii; i++) {
         alert(books[i].title);
       }
     }
  };
});
DEMO	
  
hTp://code.aaronhardy.com/require-­‐constructor	
  
Configuring	
  RequireJS	
  
/js/main.js	
  
require.config({
  baseUrl: '/another/path',
  paths: {
    'myModule': 'dirA/dirB/dirC/dirD/myModule’,
    'templates': '../templates',
    'text': 'libs/text'
  }
});

require([
  'bookshelf'
], function(bookshelf) {
  bookshelf.listBook();
});
Shimming	
  non-­‐AMD	
  libraries	
  
/js/main.js	
  
require.config({
  paths: {
     jquery: 'libs/jquery',
     underscore': 'libs/lodash',
     backbone: 'libs/backbone',
  },
  shim: {
     backbone: {
        deps: ['underscore', 'jquery'],
        exports: 'Backbone'
     },
     underscore: {
        exports: '_’
     }
  }
});
Using	
  shimmed	
  libraries	
  
/js/book.js	
  
define([
  'backbone'
], function(Backbone) {
  return Backbone.Model.extend({
     defaults: {
       genre: 'historical'
     }
  })
});
RequireJS	
  plugins	
  
Used	
  for	
  loading	
  and/or	
  transforming	
  different	
  types	
  of	
  
dependencies	
  either	
  at	
  run-­‐Ame	
  or	
  compile-­‐Ame.	
  
•  text	
  –	
  Loads	
  files	
  as	
  plain	
  text	
  
•  i18n	
  –	
  InternaAonalizaAon	
  
•  cs	
  –	
  Loads	
  and	
  compiles	
  CoffeeScript	
  
•  font	
  –	
  Loads	
  web	
  fonts	
  
•  image	
  –	
  Loads	
  image	
  files	
  
•  json	
  –	
  Loads	
  and	
  parses	
  JSON	
  
•  mdown	
  –	
  Loads	
  and	
  compiles	
  Markdown	
  
	
  
and	
  many	
  more…	
  

	
  
RequireJS	
  text	
  plugin	
  usage	
  
/js/main.js	
  
require.config({
  'paths': {
    'jquery': 'libs/jquery',
    'templates': '../templates',
    'text': 'libs/text’
  }
});

require([
  'jquery',
  'text!templates/book.tpl.html'
], function($, template) {
  $(document).ready(function() {
    $('body').html(template);
  });
});
DEMO	
  
hTp://code.aaronhardy.com/require-­‐template	
  
CondiAonal	
  dependencies	
  
require([
  'modernizr'
], function(Modernizr) {
  var drawCircle = function() { … };

  if (Modernizr.canvas) {
    drawCircle();
  } else {
    require(['excanvas'], drawCircle);
  }
});
Errbacks	
  
requirejs.config({
  enforceDefine: true,
  paths: {
    jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
  }
});

require(['jquery'], function ($) {
  //Do something with $ here
}, function (err) {
  var failedId = err.requireModules && err.requireModules[0],
  if (failedId === 'jquery') {
    requirejs.undef(failedId);

      requirejs.config({
        paths: {
          jquery: 'local/jquery'
        }
      });

      require(['jquery'], function () {});
  }
});
OpAmizaAon	
  
ConcatenaAon	
  and	
  minificaAon	
  
r.js	
  –	
  RequireJS	
  opAmizer	
  able	
  to	
  run	
  in	
  Node	
  or	
  Rhino	
  (Java)	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐opAmizaAon	
  
node	
  libs/r.js	
  -­‐o	
  baseUrl=.	
  name=main	
  out=main-­‐built.js	
  
OpAmizaAon	
  using	
  almond	
  
In	
  producAon,	
  replaces	
  RequireJS	
  and	
  is	
  bundled	
  with	
  built	
  file.	
  
•  1K	
  (almond)	
  vs	
  14K	
  (RequireJS)	
  
•  Avoids	
  two	
  separate,	
  sequenAal	
  HTTP	
  requests	
  
	
  
Biggest	
  limitaAon:	
  
•  No	
  dynamic	
  loading;	
  all	
  dependencies	
  must	
  be	
  in	
  the	
  same	
  file	
  or	
  
      loaded	
  beforehand	
  


	
  
DEMO	
  
hTp://code.aaronhardy.com/require-­‐almond	
  
node	
  libs/r.js	
  -­‐o	
  baseUrl=.	
  name=libs/almond	
  include=main	
  out=main-­‐built.js	
  
THANK	
  YOU!	
  
@aaronius	
  ·∙	
  aaronhardy.com	
  

Más contenido relacionado

La actualidad más candente

Angular Directives from Scratch
Angular Directives from ScratchAngular Directives from Scratch
Angular Directives from ScratchChristian Lilley
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
 
Arquitetura de Front-end em Aplicações de Larga Escala
Arquitetura de Front-end em Aplicações de Larga EscalaArquitetura de Front-end em Aplicações de Larga Escala
Arquitetura de Front-end em Aplicações de Larga EscalaEduardo Shiota Yasuda
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS InternalEyal Vardi
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS DirectivesChristian Lilley
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapWebFrameworks
 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsMindfire Solutions
 
Backbone.js and friends
Backbone.js and friendsBackbone.js and friends
Backbone.js and friendsGood Robot
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryPamela Fox
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용KyeongMook "Kay" Cha
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreRemy Sharp
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascriptmeet2Brains
 

La actualidad más candente (20)

Modular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScript
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
Angular Directives from Scratch
Angular Directives from ScratchAngular Directives from Scratch
Angular Directives from Scratch
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Arquitetura de Front-end em Aplicações de Larga Escala
Arquitetura de Front-end em Aplicações de Larga EscalaArquitetura de Front-end em Aplicações de Larga Escala
Arquitetura de Front-end em Aplicações de Larga Escala
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS Directives
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-Bootstrap
 
Jquery ui
Jquery uiJquery ui
Jquery ui
 
Introduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.jsIntroduction to javascript templating using handlebars.js
Introduction to javascript templating using handlebars.js
 
Backbone.js and friends
Backbone.js and friendsBackbone.js and friends
Backbone.js and friends
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
 
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
WebApps e Frameworks Javascript
WebApps e Frameworks JavascriptWebApps e Frameworks Javascript
WebApps e Frameworks Javascript
 

Similar a Dependency Management with RequireJS

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
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 

Similar a Dependency Management with RequireJS (20)

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
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
JS-05-Handlebars.ppt
JS-05-Handlebars.pptJS-05-Handlebars.ppt
JS-05-Handlebars.ppt
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Backbone js
Backbone jsBackbone js
Backbone js
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
RequireJS
RequireJSRequireJS
RequireJS
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Dependency Management with RequireJS

  • 1. DEPENDENCY     MANAGEMENT   with  RequireJS  
  • 2. HELLO   my  name  is   Aaron Hardy ·∙   @AARONIUS          AARONHARDY.COM   So8ware  Engineer,  Adobe  Digital  MarkeAng  Suite   We  enable  management,  measurement,  execu1on,  and   op1miza1on  of  digital  adver1sing  and  marke1ng.  
  • 3. What  is  dependency  management?   Loading…   The  right  code.   In  the  right  order.   At  the  right  Ame.   At  the  right  speed.     (oh  and  btw,  make  it  easy)      
  • 4. Old-­‐school  Dependency  Management   What  are  the  dependencies  here?   <script src="script3.js"></script> <script src="script1.js"></script> <script src="script13.js"></script> <script src="script7.js"></script> <script src="script6.js"></script> <script src="script12.js"></script> <script src="script4.js"></script> <script src="script11.js"></script> <script src="script5.js"></script> <script src="script9.js"></script> <script src="script8.js"></script> <script src="script10.js"></script> <script src="script2.js"></script>
  • 6. What  is  a  module?   A  structure  used  to  encapsulate  methods  and  aTributes  to  avoid   polluAng  the  global  namespace.   var Calculator = (function(){ function funkify(num) { return num * Math.random() / Math.random(); } function add(a, b, getFunky){ var sum = a + b; return getFunky ? funkify(sum) : sum; } return { add:add }; })();
  • 7. What  is  AMD?   Asynchronous  module  definiAon.       •  A  mechanism  for  defining  modules  such  that  the  module  and  its   dependencies  can  be  asynchronously  loaded.   •  Suited  for  a  browser  environment.   •  Generally  used  in  tandem  with  an  AMD  loader.  
  • 8. What  is  RequireJS?   A  JavaScript  file  and  module  loader.  Capable  of  loading  modules   defined  in  the  AMD  format  and  their  dependencies.     Not  the  only  AMD  loader  (but  unofficially  the  most  popular)   •  curl.js   •  lsjs   •  dojo   •  mootools     Open  source.  New  BSD  or  MIT  licensed.  
  • 9. Defining  a  module     /js/book.js   define({ title: "My Sister's Keeper", publisher: "Atria" });
  • 10. RequesAng  dependencies   /js/bookshelf.js   define([ 'book' ], function(book) { return { listBook: function() { alert(book.title); } }; });
  • 11. Se]ng  up  your  app   /index.html   <!DOCTYPE html> <html> <head> <title>RequireJS Example</title> <script data-main="js/main" src="js/libs/require.js"></script> </head> <body/> </html>
  • 12. Se]ng  up  your  app   /js/main.js   require([ 'bookshelf' ], function(bookshelf) { bookshelf.listBook(); });
  • 13. define()  vs.  require()   define()  completes  three  steps:   1.  Loads  the  specified  dependencies   2.  Calls  the  callback  funcAon   3.  Registers  the  return  value  from  the  callback  funcAon   require()  only  performs  #1  and  #2.  
  • 15. Defining  a  constructor  module     /js/book.js   define(function() { var Book = function(title, publisher) { this.title = title; this.publisher = publisher; }; return Book; });
  • 16. Using  a  constructor  module     /js/bookshelf.js   define([ 'book' ], function(Book) { var books = [ new Book('A Tale of Two Cities', 'Chapman & Hall'), new Book('The Good Earth', 'John Day') ]; return { listBooks: function() { for (var i = 0, ii = books.length; i < ii; i++) { alert(books[i].title); } } }; });
  • 18. Configuring  RequireJS   /js/main.js   require.config({ baseUrl: '/another/path', paths: { 'myModule': 'dirA/dirB/dirC/dirD/myModule’, 'templates': '../templates', 'text': 'libs/text' } }); require([ 'bookshelf' ], function(bookshelf) { bookshelf.listBook(); });
  • 19. Shimming  non-­‐AMD  libraries   /js/main.js   require.config({ paths: { jquery: 'libs/jquery', underscore': 'libs/lodash', backbone: 'libs/backbone', }, shim: { backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, underscore: { exports: '_’ } } });
  • 20. Using  shimmed  libraries   /js/book.js   define([ 'backbone' ], function(Backbone) { return Backbone.Model.extend({ defaults: { genre: 'historical' } }) });
  • 21. RequireJS  plugins   Used  for  loading  and/or  transforming  different  types  of   dependencies  either  at  run-­‐Ame  or  compile-­‐Ame.   •  text  –  Loads  files  as  plain  text   •  i18n  –  InternaAonalizaAon   •  cs  –  Loads  and  compiles  CoffeeScript   •  font  –  Loads  web  fonts   •  image  –  Loads  image  files   •  json  –  Loads  and  parses  JSON   •  mdown  –  Loads  and  compiles  Markdown     and  many  more…    
  • 22. RequireJS  text  plugin  usage   /js/main.js   require.config({ 'paths': { 'jquery': 'libs/jquery', 'templates': '../templates', 'text': 'libs/text’ } }); require([ 'jquery', 'text!templates/book.tpl.html' ], function($, template) { $(document).ready(function() { $('body').html(template); }); });
  • 24. CondiAonal  dependencies   require([ 'modernizr' ], function(Modernizr) { var drawCircle = function() { … }; if (Modernizr.canvas) { drawCircle(); } else { require(['excanvas'], drawCircle); } });
  • 25. Errbacks   requirejs.config({ enforceDefine: true, paths: { jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min' } }); require(['jquery'], function ($) { //Do something with $ here }, function (err) { var failedId = err.requireModules && err.requireModules[0], if (failedId === 'jquery') { requirejs.undef(failedId); requirejs.config({ paths: { jquery: 'local/jquery' } }); require(['jquery'], function () {}); } });
  • 26. OpAmizaAon   ConcatenaAon  and  minificaAon   r.js  –  RequireJS  opAmizer  able  to  run  in  Node  or  Rhino  (Java)  
  • 27. DEMO   hTp://code.aaronhardy.com/require-­‐opAmizaAon   node  libs/r.js  -­‐o  baseUrl=.  name=main  out=main-­‐built.js  
  • 28. OpAmizaAon  using  almond   In  producAon,  replaces  RequireJS  and  is  bundled  with  built  file.   •  1K  (almond)  vs  14K  (RequireJS)   •  Avoids  two  separate,  sequenAal  HTTP  requests     Biggest  limitaAon:   •  No  dynamic  loading;  all  dependencies  must  be  in  the  same  file  or   loaded  beforehand    
  • 29. DEMO   hTp://code.aaronhardy.com/require-­‐almond   node  libs/r.js  -­‐o  baseUrl=.  name=libs/almond  include=main  out=main-­‐built.js  
  • 30. THANK  YOU!   @aaronius  ·∙  aaronhardy.com  

Notas del editor

  1. node r.js -o name=main out=js/main-built.jsbaseUrl=js
  2. node r.js -o name=main out=js/main-built.jsbaseUrl=js