SlideShare a Scribd company logo
Scalable JavaScript Application Architecture




            Nicholas C. Zakas | @slicknet
Who's this guy?




 Ex-tech lead            Co-Creator                Contributor,
   Yahoo!                csslint.net            Creator of YUI Test




Author          Lead Author       Contributor           Lead Author
@slicknet
Single-page apps
Model




View           Controller
Single-page apps
        &
Multi-page apps
Building an application
      framework
An application framework
 is like a playground for your code
Provides structure around otherwise unrelated activities




                                          flickr.com/photos/osterwalder/152697503/
Isn't that what JavaScript
        libraries do?
flickr.com/photos/skistz/398429879/




A JavaScript library is like a toolbox
 You can build any number of things using the tools
Application
   Core


Base Library
Module Theory
 Everything is a module
module (n)
1 : a standard or unit of measurement
2 : the size of some one part taken as a unit of measure by which the
proportions of an architectural composition are regulated
3 a : any in a series of standardized units for use together: as (1) : a
unit of furniture or architecture (2) : an educational unit which covers
a single subject or topic b : a usually packaged functional assembly
of electronic components for use with other such assemblies
4 : an independently operable unit that is a part of the total structure
of a space vehicle
5 a : a subset of an additive group that is also a group under addition
b : a mathematical set that is a commutative group under addition
and that is closed under multiplication which is distributive from the
left or right or both by elements of a ring and for which a(bx) = (ab)x
or (xb)a = x(ba) or both where a and b are elements of the ring and x
belongs to the set

                                                      Source: Merriam-Webster Dictionary
module (n)
1 : a standard or unit of measurement
2 : the size of some one part taken as a unit of measure by which the
proportions of an architectural composition are regulated
3 a : any in a series of standardized units for use together: as (1) : a
unit of furniture or architecture (2) : an educational unit which covers
a single subject or topic b : a usually packaged functional assembly
of electronic components for use with other such assemblies
4 : an independently operable unit that is a part of the total structure
of a space vehicle
5 a : a subset of an additive group that is also a group under addition
b : a mathematical set that is a commutative group under addition
and that is closed under multiplication which is distributive from the
left or right or both by elements of a ring and for which a(bx) = (ab)x
or (xb)a = x(ba) or both where a and b are elements of the ring and x
belongs to the set

                                                      Source: Merriam-Webster Dictionary
Scalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
How does this apply to web
      applications?
web application module (n)
1 : an independent unit of functionality that is part of the total
structure of a web application




                                                                     Source: Me
Scalable JavaScript Application Architecture
Web application modules consist of
   HTML + CSS + JavaScript
Any single module should be able
to live on its own
Loose coupling allows you to make changes to
   one module without affecting the others




                              flickr.com/photos/quinnanya/3575417671/
flickr.com/photos/renfield/3414246938/




                    Each module has its own sandbox
     An interface with which the module can interact to ensure loose coupling
Module
 Module                  Module


Module     Sandbox        Module

          Application
             Core


          Base Library
Application Architecture
Modules
Sandbox
Application Core
Base Library
Module
 Module                                    Module


Module               Sandbox                  Module




  Modules have limited knowledge
  Each module knows about their sandbox and that's it
Core.register("module-name", function(sandbox){

      return {
          init: function(){
              //constructor
          },

           destroy: function(){
               //destructor
           }

      };

});
Which parts know about the web
    application being built?
None of them
Each part of the architecture is like a puzzle piece
           No single piece needs to know what the picture is
      All that matters is that the piece does its own job correctly




                                                    flickr.com/photos/generated/501445202/
What is a module's job?
Hello, I'm the weather module.
It's my job to tell you the weather.
Hello, I'm the stocks module.
It's my job to tell you about the
stock market.
Each module's job is to create a
  meaningful user experience
flickr.com/photos/eljay/2392332379/




                   The web application is created
                as a result of all parts doing their job
This doesn't mean modules can
 do whatever they want to do
           their job
flickr.com/photos/tedsblog/43433812/




         Modules are like little kids
They need a strict set of rules so they don't get into trouble
Module Rules
• Hands to yourself
   Only call your own methods or those on the sandbox
   Don't access DOM elements outside of your box
   Don't access non-native global objects
• Ask, don't take
   Anything else you need, ask the sandbox
• Don't leave your toys around
   Don't create global objects
• Don't talk to strangers
   Don't directly reference other modules
Modules must stay within their own sandboxes
                  No matter how restrictive or uncomfortable it may seem




flickr.com/photos/madaise/3406217980/
Application Architecture
Modules
Sandbox
Application Core
Base Library
Module
 Module                  Module


Module     Sandbox        Module

          Application
             Core


          Base Library
Sandbox




The sandbox ensures a consistent interface
     Modules can rely on the methods to always be there
Module
 Module                  Module


Module     Sandbox        Module

          Application
             Core


          Base Library
Module
 Module                                      Module


Module               Sandbox                   Module




  Modules only know the sandbox
   The rest of the architecture doesn't exist to them
The sandbox also acts like a security guard
Knows what the modules are allowed to access and do on the framework


                                                 flickr.com/photos/heraklit/169566548/
Core.register("module-name", function(sandbox){

      return {
          init: function(){

                //not sure if I'm allowed...
                if (sandbox.iCanHazCheezburger()){
                    alert("thx u");
                }
           },

           destroy: function(){
               //destructor
           }

      };

});
Sandbox Jobs
• Consistency
• Security
• Communication
Take the time to design the
 correct sandbox interface
       It can't change later
Application Architecture
Modules
Sandbox
Application Core
Base Library
Module
 Module                  Module


Module     Sandbox        Module

          Application
             Core


          Base Library
Application
                Core


The application core manages modules
               That's it
Application
          Core



aka Application Controller
The application core tells a module when
it should initialize and when it should shutdown
                                 flickr.com/photos/bootbearwdc/20817093/
                                 flickr.com/photos/bootbearwdc/20810695/
Core = function(){
  var moduleData = {};

 return {
     register: function(moduleId, creator){
        moduleData[moduleId] = {
           creator: creator,
           instance: null
        };
     },

       start: function(moduleId){
          moduleData[moduleId].instance =
              moduleData[moduleId].creator(new Sandbox(this));
          moduleData[moduleId].instance.init();
       },

       stop: function(moduleId){
         var data = moduleData[moduleId];
         if (data.instance){
             data.instance.destroy();
             data.instance = null;
         }
       }
  }
}();
Core = function(){

 return {
   //more code here...

    startAll: function(){
       for (var moduleId in moduleData){
         if (moduleData.hasOwnProperty(moduleId)){
           this.start(moduleId);
         }
       }
    },

    stopAll: function(){
      for (var moduleId in moduleData){
        if (moduleData.hasOwnProperty(moduleId)){
          this.stop(moduleId);
        }
      }
    },

    //more code here...
  };
}();
//register modules
Core.register("module1",   function(sandbox){   /*...*/   });
Core.register("module2",   function(sandbox){   /*...*/   });
Core.register("module3",   function(sandbox){   /*...*/   });
Core.register("module4",   function(sandbox){   /*...*/   });

//start the application by starting all modules
Core.startAll();
The application core manages
communication between modules




             flickr.com/photos/markhillary/353738538/
Scalable JavaScript Application Architecture
TimelineFilter = {
    changeFilter: function(filter){
        Timeline.applyFilter(filter);
    }
};                                        Tight
                                         Coupling
StatusPoster = {
    postStatus: function(status){
        Timeline.post(status);
    }
};                                    Tight
                                     Coupling
Timeline = {
    applyFilter: function(filter){
        //implementation
    },
    post: function(status){
        //implementation
    }
};
Core.register("timeline-filter", function(sandbox){

      return {
          changeFilter: function(filter){
              sandbox.notify({
                  type: "timeline-filter-change",
                  data: filter
              });                      Loose
          }
      };                              Coupling
});

Core.register("status-poster", function(sandbox){

      return {
          postStatus: function(statusText){
              sandbox.notify({
                  type: "new-status",
                  data: statusText
              });                           Loose
          }
      };
                                          Coupling
});
Core.register("timeline", function(sandbox){

      return {
          init: function(){
              sandbox.listen([
                  "timeline-filter-change",
                  "post-status"
              ], this.handleNotification, this);       Loose
          },                                          Coupling
           handleNotification: function(note){
               switch(note.type){
                   case "timeline-filter-change":
                       this.applyFilter(note.data);
                       return;
                   case "post-status":
                       this.post(note.data);
                       return;
               }
           }
      };
});
When modules are loosely coupled,
    removing a module doesn't break the others
No direct access to another module = no breaking should the module disappear
The application core handles errors
Uses available information to determine best course of action




                                         flickr.com/photos/brandonschauer/3168761995/
Core = function(){

  var moduleData = {}, debug = false;

  function createInstance(moduleId){
    var instance =
      moduleData[moduleId].creator(new Sandbox(this)),
      name, method;

       if (!debug){
         for (name in instance){
           method = instance[name];
           if (typeof method == "function"){
             instance[name] = function(name, method){
               return function(){
                  try { return method.apply(this, arguments);}
                  catch(ex) {log(1, name + "(): " + ex.message);}
               };
             }(name, method);
           }
         }
       }

       return instance;
  }

  //more code here

}();
Learn more
http://www.slideshare.net/nzakas/enterprise-javascript-error-handling-presentation
Application Core Jobs
•   Manage module lifecycle
•   Enable inter-module communication
•   General error handling
•   Be extensible
Why not?
Web applications change
Often in ways that you couldn't possibly anticipate
Plan for extension
flickr.com/photos/pointnshoot/1443575327/




     Anything built for extension can never be
                      obsolete
Extensions augment the capabilities of the core to keep it relevant and useful
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Extension
               Core


            Base Library
What Extensions?
•   Error handling
•   Ajax communication
•   New module capabilities
•   General utilities
•   Anything!
Ajax communication comes in different forms
     Tends to be tied to something available on the server
Request format                 Entrypoint


                    Response format



Three parts must be in sync for Ajax to work
      Modules shouldn't know anything about any of this
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Ajax/XML
               Core


            Base Library
GET ?name=value&name=value           /ajax
      Request format               Entrypoint


     Response format
<response>
   <status>ok|error</status>
   <data>
      <results>
           <result name="..." />
           <result name="..." />
      </results>
    </data>
</response>
Entrypoint
var xhr = new XMLHttpRequest();
xhr.open("get", "/ajax?name=value", true);
                                                 Request
xhr.onreadystatechange = function(){              format
  if (xhr.readyState == 4){
    if (xhr.status == 200 || xhr.status == 304){
      var statusNode = xhr.responseXML.getElementsByTagName("status")[0],
          dataNode = xhr.responseXML.getElementsByTagName("data")[0];

           if (statusNode.firstChild.nodeValue == "ok"){
             handleSuccess(processData(dataNode));
           } else {                                           Response
             handleFailure();                                  format
           }

         } else {
           handleFailure();
         }
     }

};

xhr.send(null);
                         Basic implementation
                      Lowest-level Ajax with XMLHttpRequest
Library
  reference               Entrypoint

var id = Y.io("/ajax?name=value", {
  method: "get",                           Request
  on: {                                     format
    success: function(req){
       var statusNode = req.responseXML.getElementsByTagName("status")[0],
           dataNode = req.responseXML.getElementsByTagName("data")[0];
       if (statusNode.firstChild.nodeValue == "ok"){
         handleSuccess(processData(dataNode));
       } else {                                       Response
         handleFailure();                               format
       }
    },
    failure: function(req){
       handleFailure();
    }
  }
});




              Implementation using a library
 Hides some of the ugliness but still tightly coupled to Ajax implementation
var id = sandbox.request({ name: "value" }, {
  success: function(response){
     handleSuccess(response.data);
  },
  failure: function(response){
     handleFailure();
  }
});




          Implementation using sandbox
    Passes through to core - hides all Ajax communication details
Request format                 Entrypoint


                  Response format



Ajax extension encapsulates all details
 Any of these three can change without affecting modules
GET ?name=value&name=value    /request
        Request format           Entrypoint


       Response format
{
    status: "ok|error",
    data: {
      results: [
        "...",
        "..."
      ]
    }
}
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Ajax/JSON
               Core


            Base Library
Ajax Extension Jobs
•   Hide Ajax communication details
•   Provide common request interface
•   Provide common response interface
•   Manage server failures
Application Architecture
Modules
Sandbox
Application Core
Base Library
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Extension
               Core


            Base Library
The base library provides basic functionality
                  Ironic, huh?




                Base Library
Scalable JavaScript Application Architecture
flickr.com/photos/kartik_m/2724121901/




 Most applications are too tightly coupled
            to the base library
Developers get upset when they can't touch the base library directly
High-Performance JavaScript, OSCON 2007
             Joseph Smarr, Plaxo, Inc.
Learn more
http://josephsmarr.com/2007/07/25/high-performance-javascript-oscon-2007/
Ideally, only the application core
has any idea what base library is
            being used
Module
 Module                 Module


Module     Sandbox       Module

          Application
             Core


             Dojo
Module
 Module                 Module


Module     Sandbox       Module

          Application
             Core


             YUI
Base Library Jobs
• Browser normalization
• General-purpose utilities
     Parsers/serializers for XML, JSON, etc.
     Object manipulation
     DOM manipulation
     Ajax communication
• Provide low-level extensibility
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Extension
               Core


Extension   Base Library    Extension
Architecture Knowledge
Module
  Module                   Module


Module       Sandbox        Module

            Application
Extension                   Extension
               Core


Extension   Base Library    Extension
Only the base library knows which browser
               is being used
    No other part of the architecture should need to know



                    Base Library
Only the application core knows which
      base library is being used
  No other part of the architecture should need to know



                   Application
                      Core


                  Base Library
Sandbox


                       Application
                          Core


Only the sandbox knows which application core
                is being used
      No other part of the architecture should need to know
Module
      Module                                      Module


   Module                  Sandbox                   Module




    The modules know nothing except that
            the sandbox exists
They have no knowledge of one another or the rest of the architecture
Module
  Module                     Module


Module         Sandbox        Module

              Application
Extension                     Extension
                 Core


Extension    Base Library     Extension




No part knows about the web application
Advantages
flickr.com/photos/kgoldendragon613/278240446/




Multiple different applications can be created
          with the same framework
     Minimize ramp-up time by reusing existing components
Each part can be tested separately
You just need to verify that each is doing it's unique job




                                             flickr.com/photos/misocrazy/151021636/
A scalable JavaScript architecture
allows you to replace any block
without fear of toppling the tower




                flickr.com/photos/aku-ma/2424194422/
The End
Etcetera
•My blog:      www.nczonline.net
•Twitter:      @slicknet
•These Slides: slideshare.net/nzakas

More Related Content

What's hot (20)

PDF
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Chris Richardson
 
PDF
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Chris Richardson
 
PDF
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
충섭 김
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PPT
Red Hat Ansible 적용 사례
Opennaru, inc.
 
PDF
JPA and Hibernate
elliando dias
 
PPTX
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
PDF
Introduction to RxJS
Brainhub
 
PPTX
Rxjs ppt
Christoffer Noring
 
PPTX
Microservices Architecture Part 2 Event Sourcing and Saga
Araf Karsh Hamid
 
PDF
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
PDF
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
if kakao
 
PDF
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
PDF
Kubernetes Architecture and Introduction
Stefan Schimanski
 
PDF
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
Jo Hoon
 
PPTX
쿠버네티스 ( Kubernetes ) 소개 자료
Opennaru, inc.
 
PDF
Helm 3
Matthew Farina
 
PPT
Spring mvc
Lhouceine OUHAMZA
 
PDF
Important React Hooks
Knoldus Inc.
 
Developing event-driven microservices with event sourcing and CQRS (svcc, sv...
Chris Richardson
 
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Chris Richardson
 
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
충섭 김
 
Spring Framework - Core
Dzmitry Naskou
 
Red Hat Ansible 적용 사례
Opennaru, inc.
 
JPA and Hibernate
elliando dias
 
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Introduction to RxJS
Brainhub
 
Microservices Architecture Part 2 Event Sourcing and Saga
Araf Karsh Hamid
 
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
if kakao
 
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
Kubernetes Architecture and Introduction
Stefan Schimanski
 
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
Jo Hoon
 
쿠버네티스 ( Kubernetes ) 소개 자료
Opennaru, inc.
 
Spring mvc
Lhouceine OUHAMZA
 
Important React Hooks
Knoldus Inc.
 

Similar to Scalable JavaScript Application Architecture (20)

PDF
ascitconsultancy-scalable-javascript-application-architecture for ascitconsul...
Carmor Bass
 
PPTX
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
PDF
Building a JavaScript Module Framework at Gilt
Eric Shepherd
 
PDF
Built to Last
Dan Lynch
 
PDF
An overview of Scalable Web Application Front-end
Saeid Zebardast
 
PDF
Large-Scale JavaScript Development
Addy Osmani
 
KEY
JavaScript Growing Up
David Padbury
 
PDF
IOC + Javascript
Brian Cavalier
 
PDF
Best practices for creating modular Web applications
peychevi
 
PDF
MVC pattern for widgets
Behnam Taraghi
 
PDF
JavaScript Core
François Sarradin
 
PDF
Modern UI Architecture_ Trends and Technologies in Web Development
Suresh Patidar
 
ODP
Organizing JavaScript
mcordingley
 
PPTX
Awesomeness of JavaScript…almost
Quinton Sheppard
 
PDF
HTML5 for the Silverlight Guy
David Padbury
 
PDF
Introducing Applitude: Simple Module Management
Eric Hamilton
 
PDF
Modular and Event-Driven JavaScript
Eduardo Shiota Yasuda
 
PDF
Introduction to JavaScript design patterns
Jeremy Duvall
 
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
PPTX
Single Page Applications with AngularJS 2.0
Sumanth Chinthagunta
 
ascitconsultancy-scalable-javascript-application-architecture for ascitconsul...
Carmor Bass
 
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
Building a JavaScript Module Framework at Gilt
Eric Shepherd
 
Built to Last
Dan Lynch
 
An overview of Scalable Web Application Front-end
Saeid Zebardast
 
Large-Scale JavaScript Development
Addy Osmani
 
JavaScript Growing Up
David Padbury
 
IOC + Javascript
Brian Cavalier
 
Best practices for creating modular Web applications
peychevi
 
MVC pattern for widgets
Behnam Taraghi
 
JavaScript Core
François Sarradin
 
Modern UI Architecture_ Trends and Technologies in Web Development
Suresh Patidar
 
Organizing JavaScript
mcordingley
 
Awesomeness of JavaScript…almost
Quinton Sheppard
 
HTML5 for the Silverlight Guy
David Padbury
 
Introducing Applitude: Simple Module Management
Eric Hamilton
 
Modular and Event-Driven JavaScript
Eduardo Shiota Yasuda
 
Introduction to JavaScript design patterns
Jeremy Duvall
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
Single Page Applications with AngularJS 2.0
Sumanth Chinthagunta
 
Ad

More from Nicholas Zakas (20)

PPTX
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
PPTX
Enough with the JavaScript already!
Nicholas Zakas
 
PPTX
The Pointerless Web
Nicholas Zakas
 
PPTX
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
PPTX
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PPTX
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 
PDF
Maintainable JavaScript 2011
Nicholas Zakas
 
PDF
High Performance JavaScript 2011
Nicholas Zakas
 
PDF
Mobile Web Speed Bumps
Nicholas Zakas
 
PDF
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 
PDF
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
PDF
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
PDF
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas
 
PDF
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas
 
PDF
High Performance JavaScript - Fronteers 2010
Nicholas Zakas
 
PDF
Nicholas' Performance Talk at Google
Nicholas Zakas
 
PDF
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
PDF
Performance on the Yahoo! Homepage
Nicholas Zakas
 
PDF
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas
 
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
Enough with the JavaScript already!
Nicholas Zakas
 
The Pointerless Web
Nicholas Zakas
 
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas
 
Maintainable JavaScript 2012
Nicholas Zakas
 
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 
Maintainable JavaScript 2011
Nicholas Zakas
 
High Performance JavaScript 2011
Nicholas Zakas
 
Mobile Web Speed Bumps
Nicholas Zakas
 
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas
 
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas
 
High Performance JavaScript - Fronteers 2010
Nicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas Zakas
 
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
Performance on the Yahoo! Homepage
Nicholas Zakas
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas
 
Ad

Recently uploaded (20)

PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
Learn Computer Forensics, Second Edition
AnuraShantha7
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Learn Computer Forensics, Second Edition
AnuraShantha7
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

Scalable JavaScript Application Architecture

  • 1. Scalable JavaScript Application Architecture Nicholas C. Zakas | @slicknet
  • 2. Who's this guy? Ex-tech lead Co-Creator Contributor, Yahoo! csslint.net Creator of YUI Test Author Lead Author Contributor Lead Author
  • 5. Model View Controller
  • 6. Single-page apps & Multi-page apps
  • 8. An application framework is like a playground for your code Provides structure around otherwise unrelated activities flickr.com/photos/osterwalder/152697503/
  • 9. Isn't that what JavaScript libraries do?
  • 10. flickr.com/photos/skistz/398429879/ A JavaScript library is like a toolbox You can build any number of things using the tools
  • 11. Application Core Base Library
  • 13. module (n) 1 : a standard or unit of measurement 2 : the size of some one part taken as a unit of measure by which the proportions of an architectural composition are regulated 3 a : any in a series of standardized units for use together: as (1) : a unit of furniture or architecture (2) : an educational unit which covers a single subject or topic b : a usually packaged functional assembly of electronic components for use with other such assemblies 4 : an independently operable unit that is a part of the total structure of a space vehicle 5 a : a subset of an additive group that is also a group under addition b : a mathematical set that is a commutative group under addition and that is closed under multiplication which is distributive from the left or right or both by elements of a ring and for which a(bx) = (ab)x or (xb)a = x(ba) or both where a and b are elements of the ring and x belongs to the set Source: Merriam-Webster Dictionary
  • 14. module (n) 1 : a standard or unit of measurement 2 : the size of some one part taken as a unit of measure by which the proportions of an architectural composition are regulated 3 a : any in a series of standardized units for use together: as (1) : a unit of furniture or architecture (2) : an educational unit which covers a single subject or topic b : a usually packaged functional assembly of electronic components for use with other such assemblies 4 : an independently operable unit that is a part of the total structure of a space vehicle 5 a : a subset of an additive group that is also a group under addition b : a mathematical set that is a commutative group under addition and that is closed under multiplication which is distributive from the left or right or both by elements of a ring and for which a(bx) = (ab)x or (xb)a = x(ba) or both where a and b are elements of the ring and x belongs to the set Source: Merriam-Webster Dictionary
  • 17. How does this apply to web applications?
  • 18. web application module (n) 1 : an independent unit of functionality that is part of the total structure of a web application Source: Me
  • 20. Web application modules consist of HTML + CSS + JavaScript
  • 21. Any single module should be able to live on its own
  • 22. Loose coupling allows you to make changes to one module without affecting the others flickr.com/photos/quinnanya/3575417671/
  • 23. flickr.com/photos/renfield/3414246938/ Each module has its own sandbox An interface with which the module can interact to ensure loose coupling
  • 24. Module Module Module Module Sandbox Module Application Core Base Library
  • 26. Module Module Module Module Sandbox Module Modules have limited knowledge Each module knows about their sandbox and that's it
  • 27. Core.register("module-name", function(sandbox){ return { init: function(){ //constructor }, destroy: function(){ //destructor } }; });
  • 28. Which parts know about the web application being built?
  • 30. Each part of the architecture is like a puzzle piece No single piece needs to know what the picture is All that matters is that the piece does its own job correctly flickr.com/photos/generated/501445202/
  • 31. What is a module's job?
  • 32. Hello, I'm the weather module. It's my job to tell you the weather.
  • 33. Hello, I'm the stocks module. It's my job to tell you about the stock market.
  • 34. Each module's job is to create a meaningful user experience
  • 35. flickr.com/photos/eljay/2392332379/ The web application is created as a result of all parts doing their job
  • 36. This doesn't mean modules can do whatever they want to do their job
  • 37. flickr.com/photos/tedsblog/43433812/ Modules are like little kids They need a strict set of rules so they don't get into trouble
  • 38. Module Rules • Hands to yourself  Only call your own methods or those on the sandbox  Don't access DOM elements outside of your box  Don't access non-native global objects • Ask, don't take  Anything else you need, ask the sandbox • Don't leave your toys around  Don't create global objects • Don't talk to strangers  Don't directly reference other modules
  • 39. Modules must stay within their own sandboxes No matter how restrictive or uncomfortable it may seem flickr.com/photos/madaise/3406217980/
  • 41. Module Module Module Module Sandbox Module Application Core Base Library
  • 42. Sandbox The sandbox ensures a consistent interface Modules can rely on the methods to always be there
  • 43. Module Module Module Module Sandbox Module Application Core Base Library
  • 44. Module Module Module Module Sandbox Module Modules only know the sandbox The rest of the architecture doesn't exist to them
  • 45. The sandbox also acts like a security guard Knows what the modules are allowed to access and do on the framework flickr.com/photos/heraklit/169566548/
  • 46. Core.register("module-name", function(sandbox){ return { init: function(){ //not sure if I'm allowed... if (sandbox.iCanHazCheezburger()){ alert("thx u"); } }, destroy: function(){ //destructor } }; });
  • 47. Sandbox Jobs • Consistency • Security • Communication
  • 48. Take the time to design the correct sandbox interface It can't change later
  • 50. Module Module Module Module Sandbox Module Application Core Base Library
  • 51. Application Core The application core manages modules That's it
  • 52. Application Core aka Application Controller
  • 53. The application core tells a module when it should initialize and when it should shutdown flickr.com/photos/bootbearwdc/20817093/ flickr.com/photos/bootbearwdc/20810695/
  • 54. Core = function(){ var moduleData = {}; return { register: function(moduleId, creator){ moduleData[moduleId] = { creator: creator, instance: null }; }, start: function(moduleId){ moduleData[moduleId].instance = moduleData[moduleId].creator(new Sandbox(this)); moduleData[moduleId].instance.init(); }, stop: function(moduleId){ var data = moduleData[moduleId]; if (data.instance){ data.instance.destroy(); data.instance = null; } } } }();
  • 55. Core = function(){ return { //more code here... startAll: function(){ for (var moduleId in moduleData){ if (moduleData.hasOwnProperty(moduleId)){ this.start(moduleId); } } }, stopAll: function(){ for (var moduleId in moduleData){ if (moduleData.hasOwnProperty(moduleId)){ this.stop(moduleId); } } }, //more code here... }; }();
  • 56. //register modules Core.register("module1", function(sandbox){ /*...*/ }); Core.register("module2", function(sandbox){ /*...*/ }); Core.register("module3", function(sandbox){ /*...*/ }); Core.register("module4", function(sandbox){ /*...*/ }); //start the application by starting all modules Core.startAll();
  • 57. The application core manages communication between modules flickr.com/photos/markhillary/353738538/
  • 59. TimelineFilter = { changeFilter: function(filter){ Timeline.applyFilter(filter); } }; Tight Coupling StatusPoster = { postStatus: function(status){ Timeline.post(status); } }; Tight Coupling Timeline = { applyFilter: function(filter){ //implementation }, post: function(status){ //implementation } };
  • 60. Core.register("timeline-filter", function(sandbox){ return { changeFilter: function(filter){ sandbox.notify({ type: "timeline-filter-change", data: filter }); Loose } }; Coupling }); Core.register("status-poster", function(sandbox){ return { postStatus: function(statusText){ sandbox.notify({ type: "new-status", data: statusText }); Loose } }; Coupling });
  • 61. Core.register("timeline", function(sandbox){ return { init: function(){ sandbox.listen([ "timeline-filter-change", "post-status" ], this.handleNotification, this); Loose }, Coupling handleNotification: function(note){ switch(note.type){ case "timeline-filter-change": this.applyFilter(note.data); return; case "post-status": this.post(note.data); return; } } }; });
  • 62. When modules are loosely coupled, removing a module doesn't break the others No direct access to another module = no breaking should the module disappear
  • 63. The application core handles errors Uses available information to determine best course of action flickr.com/photos/brandonschauer/3168761995/
  • 64. Core = function(){ var moduleData = {}, debug = false; function createInstance(moduleId){ var instance = moduleData[moduleId].creator(new Sandbox(this)), name, method; if (!debug){ for (name in instance){ method = instance[name]; if (typeof method == "function"){ instance[name] = function(name, method){ return function(){ try { return method.apply(this, arguments);} catch(ex) {log(1, name + "(): " + ex.message);} }; }(name, method); } } } return instance; } //more code here }();
  • 66. Application Core Jobs • Manage module lifecycle • Enable inter-module communication • General error handling • Be extensible
  • 68. Web applications change Often in ways that you couldn't possibly anticipate
  • 70. flickr.com/photos/pointnshoot/1443575327/ Anything built for extension can never be obsolete Extensions augment the capabilities of the core to keep it relevant and useful
  • 71. Module Module Module Module Sandbox Module Application Extension Extension Core Base Library
  • 72. What Extensions? • Error handling • Ajax communication • New module capabilities • General utilities • Anything!
  • 73. Ajax communication comes in different forms Tends to be tied to something available on the server
  • 74. Request format Entrypoint Response format Three parts must be in sync for Ajax to work Modules shouldn't know anything about any of this
  • 75. Module Module Module Module Sandbox Module Application Extension Ajax/XML Core Base Library
  • 76. GET ?name=value&name=value /ajax Request format Entrypoint Response format <response> <status>ok|error</status> <data> <results> <result name="..." /> <result name="..." /> </results> </data> </response>
  • 77. Entrypoint var xhr = new XMLHttpRequest(); xhr.open("get", "/ajax?name=value", true); Request xhr.onreadystatechange = function(){ format if (xhr.readyState == 4){ if (xhr.status == 200 || xhr.status == 304){ var statusNode = xhr.responseXML.getElementsByTagName("status")[0], dataNode = xhr.responseXML.getElementsByTagName("data")[0]; if (statusNode.firstChild.nodeValue == "ok"){ handleSuccess(processData(dataNode)); } else { Response handleFailure(); format } } else { handleFailure(); } } }; xhr.send(null); Basic implementation Lowest-level Ajax with XMLHttpRequest
  • 78. Library reference Entrypoint var id = Y.io("/ajax?name=value", { method: "get", Request on: { format success: function(req){ var statusNode = req.responseXML.getElementsByTagName("status")[0], dataNode = req.responseXML.getElementsByTagName("data")[0]; if (statusNode.firstChild.nodeValue == "ok"){ handleSuccess(processData(dataNode)); } else { Response handleFailure(); format } }, failure: function(req){ handleFailure(); } } }); Implementation using a library Hides some of the ugliness but still tightly coupled to Ajax implementation
  • 79. var id = sandbox.request({ name: "value" }, { success: function(response){ handleSuccess(response.data); }, failure: function(response){ handleFailure(); } }); Implementation using sandbox Passes through to core - hides all Ajax communication details
  • 80. Request format Entrypoint Response format Ajax extension encapsulates all details Any of these three can change without affecting modules
  • 81. GET ?name=value&name=value /request Request format Entrypoint Response format { status: "ok|error", data: { results: [ "...", "..." ] } }
  • 82. Module Module Module Module Sandbox Module Application Extension Ajax/JSON Core Base Library
  • 83. Ajax Extension Jobs • Hide Ajax communication details • Provide common request interface • Provide common response interface • Manage server failures
  • 85. Module Module Module Module Sandbox Module Application Extension Extension Core Base Library
  • 86. The base library provides basic functionality Ironic, huh? Base Library
  • 88. flickr.com/photos/kartik_m/2724121901/ Most applications are too tightly coupled to the base library Developers get upset when they can't touch the base library directly
  • 89. High-Performance JavaScript, OSCON 2007 Joseph Smarr, Plaxo, Inc.
  • 91. Ideally, only the application core has any idea what base library is being used
  • 92. Module Module Module Module Sandbox Module Application Core Dojo
  • 93. Module Module Module Module Sandbox Module Application Core YUI
  • 94. Base Library Jobs • Browser normalization • General-purpose utilities  Parsers/serializers for XML, JSON, etc.  Object manipulation  DOM manipulation  Ajax communication • Provide low-level extensibility
  • 95. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension
  • 97. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension
  • 98. Only the base library knows which browser is being used No other part of the architecture should need to know Base Library
  • 99. Only the application core knows which base library is being used No other part of the architecture should need to know Application Core Base Library
  • 100. Sandbox Application Core Only the sandbox knows which application core is being used No other part of the architecture should need to know
  • 101. Module Module Module Module Sandbox Module The modules know nothing except that the sandbox exists They have no knowledge of one another or the rest of the architecture
  • 102. Module Module Module Module Sandbox Module Application Extension Extension Core Extension Base Library Extension No part knows about the web application
  • 104. flickr.com/photos/kgoldendragon613/278240446/ Multiple different applications can be created with the same framework Minimize ramp-up time by reusing existing components
  • 105. Each part can be tested separately You just need to verify that each is doing it's unique job flickr.com/photos/misocrazy/151021636/
  • 106. A scalable JavaScript architecture allows you to replace any block without fear of toppling the tower flickr.com/photos/aku-ma/2424194422/
  • 108. Etcetera •My blog: www.nczonline.net •Twitter: @slicknet •These Slides: slideshare.net/nzakas