SlideShare a Scribd company logo
RequireJS for modular
   JavaScript code                     this presentation is about
                                       Require JS.

                                       * why use it
                                       * How it works

     Thomas Lundström, Softhouse       * How it’s used
                                       * How to start using it

         @thomaslundstrom              Let’s start with some of the
                                       problems I’ve seen (and been
                                       guilty of) in web apps that
                                       use JavaScript during my

              April 16, 2012
                                       tenure as a consultant


   Scandinavian Developer Conference
JS is big         Even if you don’t run a JS
                                 framework, just “some HTML and
                                 JS”, you often have rather large JS
                                 files - quite often spaghetti-like
                                 with a large number of functions
                                 calling each other.

                                 New JS-heavy apps often use one or
                                 more of the JS Frameworks that
                                 exist today, e.g. Backbone,
                                 Knockout, Ember, SproutCore etc,
                                 making it more and more important
                                 to think about componentizing and
                                 structuring your code.




• Web-apps today contain large amounts of
  JavaScript
Dependency
management is hard
                Top-level functions in the
                global namespace often lead to
                circular dependencies (which
                aren’t easily spotted - you
                basically need to wade through
                the JS code to find all
                dependencies).

                2 Files - 5 different functions
                calling each other
Dev/deploy conflict
                 Requirements conflict bet ween
                 development and deployment:

                 Devs want small discrete files
                 since it’s easier to debug and
                 test small units.
                 Additionally, using large files
                 with a script tag doesn’t scale
                 in larger apps with large
                 number of developers: e.g.
                 merge hell in version control

                 Deployment should be done on
                 large files since we don’t want
                 the browser to load lots of files
                 - the latency gives us slowly
                 loaded pages
Require tries to solve the problems with
            growing JS code bases by introducing the
            “module” abstraction.

            In its core, modules exposes an interface
            and has dependencies. You ask RequireJS for
            a module, and RequireJS traces and
            instantiates its dependencies (including
            transitive dependencies) before
            instantiating the module you wish to use.

            Why modules?
            Modules are (or, should be) small => easy to
            understand => easy to change + easy to test




RequireJS
Define
        This is a quite standard logger that every
        site needs. This one works with IE (where
        console.log throws an error if the
        development tools aren’t enabled).

        You use the define function to define a
        module. The API is called AMD -
        asyncronous module definition.

        The file name (modules/logger) is the
        name of the module.

        Dependencies are stated in the array in
        the beginning of the function call. This
        one has no dependencies - the array is
        empty

        The function @ param2 is a factory
        function that’s executed when we
        instantiate this module

        The returned object is fed as an argument
        to the module requiring this module as a
        dependency. Here, the factory returns an
        object containing only one function: log
        (msg).

        Note: we don’t clobber the global scope
        since everything in this module is hidden
        by the scope of the anonymous function.
Define   A module that takes t wo other
        modules as dependencies.
        The names of the dependencies are the
        module names, e.g. “modules/logger”
        from the previous slide

        The returned objects from the
        dependencies are injected into our
        factory function. (Logger returns an
        object containing the log function.)
Require


          The require() call is the main
          entry point to the modules
          defined by the define() call.

          The first argument is an
          array containing all module
          names we wish to load.

          The anonymous function is a
          callback that’s called after
          the required modules and
          their dependencies have been
          loaded. The args to the
          function is the required
          modules.
End result
             The different modules in
             the diagram have defined
             dependencies, a clean
             interface (i.e. the
             returned object) and are
             easy to unit-test.
Firebug



          An image from firebug with the
          modules from the previous slide.

          Current problem: we have too many
          files, leading to slow loading times.

          Require JS optimizer to the rescue!
Firebug (optimized)




           The RequireJS optimizer compiles a top-level module (in
           our case, “module1.js”) and its dependencies (recursively)
           together into one file.

           The file is also uglified (see example below).

           -> One file per top-level module with minimal footprint
legacy JS files = large,
                  spaghetti, global scope




Introducing RequireJS
  with legacy JS files
Single JS file   If you are using only one js file
                         (or you have no cross-refs
                         bet ween different stand-alone
                         js files): you’re in luck.



• One file = one module   This requires that no-one
                         accesses the JS functions that
                         are defined in the single JS file
                         (e.g. literal click handlers on
                         buttons/links etc).

                         It’s rather uncommon, sadly.

                         BUT: If we have this we can
                         rather easily introduce
                         RequireJS in the application.

                         Let the entire file be your module
                         as a start.
                         Then, refactor small pieces of
                         functionality into sub-modules
                         as you go along.
Interconnected files



The problem here is the circular dependency bet ween file A and B at: file_a_2() -> file_b_2() -> file_a_1().

This state is rather common. There is no super-simple solution if we have these circular dependencies bet ween
file A and B.

This issue doesn’t only occur if we have different functions calling each other. We could also have one file and
a literal click handler on a button/a-link with the function name stated in HTML.

To start solving this issue, we can modularize and export only the globally used functions. (In next slide.)
Interconnected files




in the t wo highlighted rows we export the cross-ref’d functions to the global namespace. These global functions are then called at
lines 9 and 13 in file A and B respectively.

The next step is to refactor out file_a_1 and file_b_2 into separate modules. This is left as an excercise to the reader. The reason for
      extracting this is that we don’t want to use circular references bet ween modules.
Thanks!                RequireJS is Open Source,
                                    dev @ GitHub

                                    I’ll post this presentation
                                    + some samples at my


• RequireJS.org                     blog.




• Thomas Lundström, Softhouse
• thomas.lundstrom@softhouse.se
• @thomaslundstrom
• http://blog.thomaslundstrom.com

More Related Content

What's hot (20)

MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
codeinmotion
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework Reaction
jbandi
 
Open Social Summit Korea
Open Social Summit KoreaOpen Social Summit Korea
Open Social Summit Korea
Arne Roomann-Kurrik
 
JSP overview
JSP overviewJSP overview
JSP overview
Amisha Narsingani
 
RequireJS
RequireJSRequireJS
RequireJS
Tim Doherty
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
danwrong
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
dhananajay95
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
APSMIND TECHNOLOGY PVT LTD.
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
jbandi
 
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Hugh Anderson
 
Advanced java programming-contents
Advanced java programming-contentsAdvanced java programming-contents
Advanced java programming-contents
Self-Employed
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
Client-Side Packages
Client-Side PackagesClient-Side Packages
Client-Side Packages
Domenic Denicola
 
netbeans
netbeansnetbeans
netbeans
tutorialsruby
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
Soba Arjun
 
Jsp lecture
Jsp lectureJsp lecture
Jsp lecture
Tata Consultancy Services
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
Hitesh-Java
 
JavaScript Modules in Practice
JavaScript Modules in PracticeJavaScript Modules in Practice
JavaScript Modules in Practice
Maghdebura
 
MVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on RailsMVC Demystified: Essence of Ruby on Rails
MVC Demystified: Essence of Ruby on Rails
codeinmotion
 
From User Action to Framework Reaction
From User Action to Framework ReactionFrom User Action to Framework Reaction
From User Action to Framework Reaction
jbandi
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
danwrong
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
dhananajay95
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
jbandi
 
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVMAsynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Hugh Anderson
 
Advanced java programming-contents
Advanced java programming-contentsAdvanced java programming-contents
Advanced java programming-contents
Self-Employed
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
Soba Arjun
 
JavaScript Modules in Practice
JavaScript Modules in PracticeJavaScript Modules in Practice
JavaScript Modules in Practice
Maghdebura
 

Viewers also liked (9)

Modularize JavaScript with RequireJS
Modularize JavaScript with RequireJSModularize JavaScript with RequireJS
Modularize JavaScript with RequireJS
Minh Hoang
 
Require.JS
Require.JSRequire.JS
Require.JS
Ivano Malavolta
 
Meet Handlebar
Meet HandlebarMeet Handlebar
Meet Handlebar
Handlebar Publishing
 
Requirejs
RequirejsRequirejs
Requirejs
sioked
 
Require JS
Require JSRequire JS
Require JS
Imaginea
 
Require js
Require jsRequire js
Require js
Nirbhay Kundan
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
RequireJS
RequireJSRequireJS
RequireJS
Sebastiano Armeli
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
Ad

Similar to Using RequireJS for Modular JavaScript Code (20)

AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
Mike Wilcox
 
JS Essence
JS EssenceJS Essence
JS Essence
Uladzimir Piatryka
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
Johan Nilsson
 
High quality Front-End
High quality Front-EndHigh quality Front-End
High quality Front-End
David Simons
 
Require js training
Require js trainingRequire js training
Require js training
Dr. Awase Khirni Syed
 
PLOG - Modern Javascripting with Plone
PLOG - Modern Javascripting with PlonePLOG - Modern Javascripting with Plone
PLOG - Modern Javascripting with Plone
Rok Garbas
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Jayanga V. Liyanage
 
Modular JavaScript
Modular JavaScriptModular JavaScript
Modular JavaScript
Andrew Eisenberg
 
Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012
Adam Mokan
 
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane EcosystemDownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
FITC
 
Node.JS
Node.JSNode.JS
Node.JS
Kristaps Kūlis
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
Yoshiki Shibukawa
 
Building a JavaScript Module Framework at Gilt
Building a JavaScript Module Framework at GiltBuilding a JavaScript Module Framework at Gilt
Building a JavaScript Module Framework at Gilt
Eric Shepherd
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Javascript Dependency Management
Javascript Dependency ManagementJavascript Dependency Management
Javascript Dependency Management
Sean Duncan
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
xMartin12
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
Nirvanic Labs
 
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane EcosystemDownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
FITC
 
AMD - Why, What and How
AMD - Why, What and HowAMD - Why, What and How
AMD - Why, What and How
Mike Wilcox
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
Johan Nilsson
 
High quality Front-End
High quality Front-EndHigh quality Front-End
High quality Front-End
David Simons
 
PLOG - Modern Javascripting with Plone
PLOG - Modern Javascripting with PlonePLOG - Modern Javascripting with Plone
PLOG - Modern Javascripting with Plone
Rok Garbas
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012Single Page Applications - Desert Code Camp 2012
Single Page Applications - Desert Code Camp 2012
Adam Mokan
 
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane EcosystemDownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
FITC
 
Expert JavaScript Programming
Expert JavaScript ProgrammingExpert JavaScript Programming
Expert JavaScript Programming
Yoshiki Shibukawa
 
Building a JavaScript Module Framework at Gilt
Building a JavaScript Module Framework at GiltBuilding a JavaScript Module Framework at Gilt
Building a JavaScript Module Framework at Gilt
Eric Shepherd
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Javascript Dependency Management
Javascript Dependency ManagementJavascript Dependency Management
Javascript Dependency Management
Sean Duncan
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
xMartin12
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
Nirvanic Labs
 
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane EcosystemDownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
FITC
 
Ad

More from Thomas Lundström (6)

Railsify your web development
Railsify your web developmentRailsify your web development
Railsify your web development
Thomas Lundström
 
Bdd for Web Applications at TelecomCity DevCon 2010
Bdd for Web Applications at TelecomCity DevCon 2010Bdd for Web Applications at TelecomCity DevCon 2010
Bdd for Web Applications at TelecomCity DevCon 2010
Thomas Lundström
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
Thomas Lundström
 
Bdd For Web Applications from Scandinavian Developer Conference 2010
Bdd For Web Applications from Scandinavian Developer Conference 2010Bdd For Web Applications from Scandinavian Developer Conference 2010
Bdd For Web Applications from Scandinavian Developer Conference 2010
Thomas Lundström
 
BDD approaches for web development at Agile Testing Days 2009
BDD approaches for web development at Agile Testing Days 2009BDD approaches for web development at Agile Testing Days 2009
BDD approaches for web development at Agile Testing Days 2009
Thomas Lundström
 
Cucumber mot .NET-kod
Cucumber mot .NET-kodCucumber mot .NET-kod
Cucumber mot .NET-kod
Thomas Lundström
 
Railsify your web development
Railsify your web developmentRailsify your web development
Railsify your web development
Thomas Lundström
 
Bdd for Web Applications at TelecomCity DevCon 2010
Bdd for Web Applications at TelecomCity DevCon 2010Bdd for Web Applications at TelecomCity DevCon 2010
Bdd for Web Applications at TelecomCity DevCon 2010
Thomas Lundström
 
Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)Ruby for C#-ers (ScanDevConf 2010)
Ruby for C#-ers (ScanDevConf 2010)
Thomas Lundström
 
Bdd For Web Applications from Scandinavian Developer Conference 2010
Bdd For Web Applications from Scandinavian Developer Conference 2010Bdd For Web Applications from Scandinavian Developer Conference 2010
Bdd For Web Applications from Scandinavian Developer Conference 2010
Thomas Lundström
 
BDD approaches for web development at Agile Testing Days 2009
BDD approaches for web development at Agile Testing Days 2009BDD approaches for web development at Agile Testing Days 2009
BDD approaches for web development at Agile Testing Days 2009
Thomas Lundström
 

Recently uploaded (20)

No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptxFIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FMESupporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptxFIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FMESupporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 

Using RequireJS for Modular JavaScript Code

  • 1. RequireJS for modular JavaScript code this presentation is about Require JS. * why use it * How it works Thomas Lundström, Softhouse * How it’s used * How to start using it @thomaslundstrom Let’s start with some of the problems I’ve seen (and been guilty of) in web apps that use JavaScript during my April 16, 2012 tenure as a consultant Scandinavian Developer Conference
  • 2. JS is big Even if you don’t run a JS framework, just “some HTML and JS”, you often have rather large JS files - quite often spaghetti-like with a large number of functions calling each other. New JS-heavy apps often use one or more of the JS Frameworks that exist today, e.g. Backbone, Knockout, Ember, SproutCore etc, making it more and more important to think about componentizing and structuring your code. • Web-apps today contain large amounts of JavaScript
  • 3. Dependency management is hard Top-level functions in the global namespace often lead to circular dependencies (which aren’t easily spotted - you basically need to wade through the JS code to find all dependencies). 2 Files - 5 different functions calling each other
  • 4. Dev/deploy conflict Requirements conflict bet ween development and deployment: Devs want small discrete files since it’s easier to debug and test small units. Additionally, using large files with a script tag doesn’t scale in larger apps with large number of developers: e.g. merge hell in version control Deployment should be done on large files since we don’t want the browser to load lots of files - the latency gives us slowly loaded pages
  • 5. Require tries to solve the problems with growing JS code bases by introducing the “module” abstraction. In its core, modules exposes an interface and has dependencies. You ask RequireJS for a module, and RequireJS traces and instantiates its dependencies (including transitive dependencies) before instantiating the module you wish to use. Why modules? Modules are (or, should be) small => easy to understand => easy to change + easy to test RequireJS
  • 6. Define This is a quite standard logger that every site needs. This one works with IE (where console.log throws an error if the development tools aren’t enabled). You use the define function to define a module. The API is called AMD - asyncronous module definition. The file name (modules/logger) is the name of the module. Dependencies are stated in the array in the beginning of the function call. This one has no dependencies - the array is empty The function @ param2 is a factory function that’s executed when we instantiate this module The returned object is fed as an argument to the module requiring this module as a dependency. Here, the factory returns an object containing only one function: log (msg). Note: we don’t clobber the global scope since everything in this module is hidden by the scope of the anonymous function.
  • 7. Define A module that takes t wo other modules as dependencies. The names of the dependencies are the module names, e.g. “modules/logger” from the previous slide The returned objects from the dependencies are injected into our factory function. (Logger returns an object containing the log function.)
  • 8. Require The require() call is the main entry point to the modules defined by the define() call. The first argument is an array containing all module names we wish to load. The anonymous function is a callback that’s called after the required modules and their dependencies have been loaded. The args to the function is the required modules.
  • 9. End result The different modules in the diagram have defined dependencies, a clean interface (i.e. the returned object) and are easy to unit-test.
  • 10. Firebug An image from firebug with the modules from the previous slide. Current problem: we have too many files, leading to slow loading times. Require JS optimizer to the rescue!
  • 11. Firebug (optimized) The RequireJS optimizer compiles a top-level module (in our case, “module1.js”) and its dependencies (recursively) together into one file. The file is also uglified (see example below). -> One file per top-level module with minimal footprint
  • 12. legacy JS files = large, spaghetti, global scope Introducing RequireJS with legacy JS files
  • 13. Single JS file If you are using only one js file (or you have no cross-refs bet ween different stand-alone js files): you’re in luck. • One file = one module This requires that no-one accesses the JS functions that are defined in the single JS file (e.g. literal click handlers on buttons/links etc). It’s rather uncommon, sadly. BUT: If we have this we can rather easily introduce RequireJS in the application. Let the entire file be your module as a start. Then, refactor small pieces of functionality into sub-modules as you go along.
  • 14. Interconnected files The problem here is the circular dependency bet ween file A and B at: file_a_2() -> file_b_2() -> file_a_1(). This state is rather common. There is no super-simple solution if we have these circular dependencies bet ween file A and B. This issue doesn’t only occur if we have different functions calling each other. We could also have one file and a literal click handler on a button/a-link with the function name stated in HTML. To start solving this issue, we can modularize and export only the globally used functions. (In next slide.)
  • 15. Interconnected files in the t wo highlighted rows we export the cross-ref’d functions to the global namespace. These global functions are then called at lines 9 and 13 in file A and B respectively. The next step is to refactor out file_a_1 and file_b_2 into separate modules. This is left as an excercise to the reader. The reason for extracting this is that we don’t want to use circular references bet ween modules.
  • 16. Thanks! RequireJS is Open Source, dev @ GitHub I’ll post this presentation + some samples at my • RequireJS.org blog. • Thomas Lundström, Softhouse • [email protected] • @thomaslundstrom • http://blog.thomaslundstrom.com