SlideShare a Scribd company logo
Architecting single-page Web apps
Zohar Arad. June 2011
Quick intro
 Front-end architect and developer
 Been building websites since 2004
 3 years as Metacafe’s leading front-end developer
 MooTools, Rails, Ruby, Mac, Linux enthusiast
 Front-end is my main game. I also know the back-end quite
 well
Single-page Web apps.
We’re going to cover
 Basic concepts
 Client-server relationship
 Routing
 Views and content rendering
 Global event handling
We’re going to cover
 Dependency management
 Code initialization and execution
 Form handling
 Final thoughts
Basic concepts
 One view, many partials
 Rely on async requests for fetching and sending data
 No page refresh - Update content in place
 Desktop application user-interaction model
 RESTful client-server communication
Problems and challenges
 When are various components included and initialized?
 How do we define generic interaction for separate
 components?
 How do we send, receive and render data asynchronously?
 How do we avoid re-initialization of existing components?
 What happens when things break?
A word of caution
 Single-page applications should work without Javascript.


 If you only rely on Javascript without gracefully degrading to
 non-javascript functionality you’re doing it wrong!


 This is true most of the times...
Client-server relationship
Client-server relationships
 Most single-page apps require a server to handle data and
 business logic (CouchApps excluded)
 We start planning and building the server-side
 We define routes, controllers, actions and views as we
 would for ordinary web apps
Why??
No server = no application
We need solid conventions for both sides of the application
The client is a consumer, not a service provider
Give it a REST
Planning routes
REST
Your client and server should agree how to communicate
REST helps you define which resource represents which
action or state
Your URLs should be defined on the server and
implemented by the client
Do not reinvent the wheel (URL generators)
REST and HTTP
Remember HTTP verbs and conventions
GET is used to read data
POST / PUT are used to write / update data
DELETE is used to remove data
Data rendering
Views and templates. Sans-rain-deer
Rendering HTML
View / partial paradigm
 Full view is rendered in normal request
 Partial view is rendered in XHR
DRY - write your HTML only once
Rendering HTML
Server side should generate HTML whenever possible
 Why should the client generate HTML?
 We need to manage HTML generation in one place
 Localization is easier on the server-side
 Server-side performance is absolute and known
What about JSON
JSON.... We love you man!
Rendering HTML
You need to ask yourself why should you use JSON instead
of HTML to generate views.


You need generic support on both server and client
You need to justify the overhead of HTML generation
Rendering HTML
Seriously - If you can handle HTML on the server, do it.


Keep is simple and don’t repeat yourself!
But I love JSON
Seriously, just look at the guy!
Data passing with JSON
 We’d use JSON to pass data to the client when
  We’re not rendering HTML (e.g. forms, APIs)
  There’s no other option
  Bandwidth is expensive
  Business logic is in the browser
Global events
One event to rule them all and in the browser bind them
Global Events
 We have bits of HTML loaded asynchronously
 We already initialized event handles on replaced HTML
 We want to avoid re-binding event handles with each DOM
 update
Global Events
 function globalClickHandler(e){

     var tgt = $(e.target);

     do {

      tag = tgt.get('tag');

       if (tag === 'a') { /** do something with link **/}

      tgt = tgt.getParent();

     } while (tag !== 'body');

 }

 document.addEvent(‘click’,globalClickHandler);
Global Events
 We can use the same principle to any other event we want
 to handle globally
 We can handle form submission for example
 Keyboard events
 Form widgets events
Global Events
 Issues to remember:
  We have some redundant DOM traversal
  We should strive to unbind events on unload
  Too much is no good (don’t over do it)
Dependency Management
Dependency Management
Three approaches
 Brute and Hungry
 Requires
 Script tags
Dependency Management
Brute and Hungry
 We load everything when page loads
 We need to ensure things are packed nicely
   Jammit or Sprockets
 Large file limitations (caching, parsing, network)
 Change in one file forces full cache purge
Dependency Management
Requires
 Use a JS dependency library (require.js, head.js)
 script-ready support
 load only when needed
 requires a bit more logic to ensure things run after
 requires
Dependency Management
Script tags
 Fetch JS script tags with HTML
 Add to DOM once
 Binds view and JS (good or bad?)
 Readiness and requiring management needed
Dependency Management
Brute and Hungry - Small JS apps / non-mobile apps
Requires / Script tags - Larger / more complex apps
Requires are probably the best solution out there
 Flexible
 Functional and Intuitive
 Penalties are “less” severe
Initialization and Execution
Executing things without breaking your neck
Initialization and execution
 Our code needs to run at certain points or respond to
 certain user interactions.


 How do we know when to initialize and execute the relevant
 bits of code?
Initialization and execution
 We initialize our application’s entry point module on DOM
 ready
 If we’re using requires, we can initialize required modules
 when they’re required
Initialization and execution
 We have a global handler for async requests
  We can execute response callbacks based on request
  URL
  We can return a bit of Javascript with each response that
  will be executed when the content is rendered
Initialization and execution
 Finally, we can use an Initializer pattern to call various
 modules based on some convention:
   We need module construction and destruction
   We know what action was performed on the server (e.g.
   controller name and action name)
Initialization and execution
 var Initializer = {
   last_action:null,
   init:function(action){
       if(this.last_action && typeof(this.Destructors[this.last_action]) === ‘function’){
           this.Destructors[this.last_action]();
       }
       if(typeof(this.Constructors[action]) === ‘function’){
           this.Constructors[action]();
       }
       this.last_action = action;
   }
 };
Initialization and execution
 Initializer.Constructors = {};
 Initializer.Destructors = {};


 /** Somewhere in a module **/


 Initializer.Constructors.Gallery = function(){....}
 Initializer.Destructors.Gallery = function(){....}
Initialization and execution
 /** Our global request handler **/
 var Request = {
     get:function(url){
         var xhr = new Request({
           url:url,
           onSuccess:function(response){
               // render response here
               Initializer.init(url.split(‘/’)[1]);
           }
         });
         xhr.get();
     }
 }
Handling forms
 Handle GET and POST requests separately
 Form validation is the server’s job!!!
 The client should assist the user to fill correct values
 Use server-side validation errors in the client
 Rely on HTTP error statuses to handle success / failure
Handling forms
 You can have a global form handler, similar to your global
 request handler
 Async responses should be:
  JSON when we check success / failure
  HTML when we render something after submission
 Define a coherent API to pass data from server to client on
 form submission
Final thoughts
 We didn’t talk about
  Performance, MVC, Couch Apps, templates
 Do what’s right based on your requirements
 Learn a goddamn server-side framework
Final thoughts
 Design for simplicity
 Don’t repeat yourself and don’t reinvent the wheel
 Start small and grow larger (modules anyone?)
 Define developer-friendly conventions and follow them

More Related Content

What's hot

Wordcamp Toronto Presentation
Wordcamp Toronto PresentationWordcamp Toronto Presentation
Wordcamp Toronto Presentation
Roy Sivan
 
ASP.NET MVC and ajax
ASP.NET MVC and ajax ASP.NET MVC and ajax
ASP.NET MVC and ajax
Brij Mishra
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
Jeremy Likness
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC
Joe Wilson
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
Rajat Pratap Singh
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
rudib
 
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web AppsSenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
Sencha
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High GearASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
Kevin Griffin
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
Manvendra Singh
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
Raja V
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
Fajar Baskoro
 
Web application intro
Web application introWeb application intro
Web application intro
Tobias Pfeiffer
 
Ember.js for Big Profit
Ember.js for Big ProfitEmber.js for Big Profit
Ember.js for Big Profit
CodeCore
 
Increase automation to rest
Increase automation to restIncrease automation to rest
Increase automation to rest
vodQA
 
Optimizing Content Managed Rich JavaScript Apps
Optimizing Content Managed Rich JavaScript AppsOptimizing Content Managed Rich JavaScript Apps
Optimizing Content Managed Rich JavaScript Apps
Magnolia
 
AJAX
AJAXAJAX
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using Protractor
Kasun Kodagoda
 

What's hot (20)

Wordcamp Toronto Presentation
Wordcamp Toronto PresentationWordcamp Toronto Presentation
Wordcamp Toronto Presentation
 
ASP.NET MVC and ajax
ASP.NET MVC and ajax ASP.NET MVC and ajax
ASP.NET MVC and ajax
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVC Introduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Async
AsyncAsync
Async
 
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web AppsSenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High GearASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
Rails Concept
Rails ConceptRails Concept
Rails Concept
 
Web application intro
Web application introWeb application intro
Web application intro
 
Ember.js for Big Profit
Ember.js for Big ProfitEmber.js for Big Profit
Ember.js for Big Profit
 
Increase automation to rest
Increase automation to restIncrease automation to rest
Increase automation to rest
 
Optimizing Content Managed Rich JavaScript Apps
Optimizing Content Managed Rich JavaScript AppsOptimizing Content Managed Rich JavaScript Apps
Optimizing Content Managed Rich JavaScript Apps
 
AJAX
AJAXAJAX
AJAX
 
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using Protractor
 

Viewers also liked

Rolling Your Own CSS Methodology
Rolling Your Own CSS MethodologyRolling Your Own CSS Methodology
Rolling Your Own CSS Methodology
FITC
 
Performance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomasPerformance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomas
David Amend
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS MethodologyZohar Arad
 
DIGIT Noe 2016 - Overview of front end development today
DIGIT Noe 2016 - Overview of front end development todayDIGIT Noe 2016 - Overview of front end development today
DIGIT Noe 2016 - Overview of front end development today
Bojan Veljanovski
 
Our Best Practices Are Killing Us
Our Best Practices Are Killing UsOur Best Practices Are Killing Us
Our Best Practices Are Killing Us
Nicole Sullivan
 
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
Jer Clarke
 
Object Oriented CSS
Object Oriented CSSObject Oriented CSS
Object Oriented CSS
Nicole Sullivan
 
The benefits of BEM CSS
The benefits of BEM CSSThe benefits of BEM CSS
The benefits of BEM CSS
Bob Donderwinkel
 

Viewers also liked (8)

Rolling Your Own CSS Methodology
Rolling Your Own CSS MethodologyRolling Your Own CSS Methodology
Rolling Your Own CSS Methodology
 
Performance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomasPerformance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomas
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
DIGIT Noe 2016 - Overview of front end development today
DIGIT Noe 2016 - Overview of front end development todayDIGIT Noe 2016 - Overview of front end development today
DIGIT Noe 2016 - Overview of front end development today
 
Our Best Practices Are Killing Us
Our Best Practices Are Killing UsOur Best Practices Are Killing Us
Our Best Practices Are Killing Us
 
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
DRY CSS A don’t-repeat-yourself methodology for creating efficient, unified a...
 
Object Oriented CSS
Object Oriented CSSObject Oriented CSS
Object Oriented CSS
 
The benefits of BEM CSS
The benefits of BEM CSSThe benefits of BEM CSS
The benefits of BEM CSS
 

Similar to Architecting single-page front-end apps

Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassSpike Brehm
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
zonathen
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
Matthias Noback
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
Clarence Ngoh
 
SocketStream
SocketStreamSocketStream
SocketStream
Paul Jensen
 
React loadable
React loadableReact loadable
React loadable
George Bukhanov
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
SolTech, Inc.
 
Intro to ember.js
Intro to ember.jsIntro to ember.js
Intro to ember.js
Leo Hernandez
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
Troy Miles
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Web Development Today
Web Development TodayWeb Development Today
Web Development Today
bretticus
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
Divyang Bhambhani
 
Magento's Imagine eCommerce Conference: Do You Queue?
Magento's Imagine eCommerce Conference: Do You Queue?Magento's Imagine eCommerce Conference: Do You Queue?
Magento's Imagine eCommerce Conference: Do You Queue?varien
 

Similar to Architecting single-page front-end apps (20)

Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)Having Fun Building Web Applications (Day 1 Slides)
Having Fun Building Web Applications (Day 1 Slides)
 
SocketStream
SocketStreamSocketStream
SocketStream
 
React loadable
React loadableReact loadable
React loadable
 
Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
 
PPT
PPTPPT
PPT
 
Intro to ember.js
Intro to ember.jsIntro to ember.js
Intro to ember.js
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Web Development Today
Web Development TodayWeb Development Today
Web Development Today
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Magento's Imagine eCommerce Conference: Do You Queue?
Magento's Imagine eCommerce Conference: Do You Queue?Magento's Imagine eCommerce Conference: Do You Queue?
Magento's Imagine eCommerce Conference: Do You Queue?
 

Recently uploaded

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 

Architecting single-page front-end apps

  • 1. Architecting single-page Web apps Zohar Arad. June 2011
  • 2. Quick intro Front-end architect and developer Been building websites since 2004 3 years as Metacafe’s leading front-end developer MooTools, Rails, Ruby, Mac, Linux enthusiast Front-end is my main game. I also know the back-end quite well
  • 4. We’re going to cover Basic concepts Client-server relationship Routing Views and content rendering Global event handling
  • 5. We’re going to cover Dependency management Code initialization and execution Form handling Final thoughts
  • 6. Basic concepts One view, many partials Rely on async requests for fetching and sending data No page refresh - Update content in place Desktop application user-interaction model RESTful client-server communication
  • 7. Problems and challenges When are various components included and initialized? How do we define generic interaction for separate components? How do we send, receive and render data asynchronously? How do we avoid re-initialization of existing components? What happens when things break?
  • 8. A word of caution Single-page applications should work without Javascript. If you only rely on Javascript without gracefully degrading to non-javascript functionality you’re doing it wrong! This is true most of the times...
  • 10. Client-server relationships Most single-page apps require a server to handle data and business logic (CouchApps excluded) We start planning and building the server-side We define routes, controllers, actions and views as we would for ordinary web apps
  • 11. Why?? No server = no application We need solid conventions for both sides of the application The client is a consumer, not a service provider
  • 12. Give it a REST Planning routes
  • 13. REST Your client and server should agree how to communicate REST helps you define which resource represents which action or state Your URLs should be defined on the server and implemented by the client Do not reinvent the wheel (URL generators)
  • 14. REST and HTTP Remember HTTP verbs and conventions GET is used to read data POST / PUT are used to write / update data DELETE is used to remove data
  • 15. Data rendering Views and templates. Sans-rain-deer
  • 16. Rendering HTML View / partial paradigm Full view is rendered in normal request Partial view is rendered in XHR DRY - write your HTML only once
  • 17. Rendering HTML Server side should generate HTML whenever possible Why should the client generate HTML? We need to manage HTML generation in one place Localization is easier on the server-side Server-side performance is absolute and known
  • 18. What about JSON JSON.... We love you man!
  • 19. Rendering HTML You need to ask yourself why should you use JSON instead of HTML to generate views. You need generic support on both server and client You need to justify the overhead of HTML generation
  • 20. Rendering HTML Seriously - If you can handle HTML on the server, do it. Keep is simple and don’t repeat yourself!
  • 21. But I love JSON Seriously, just look at the guy!
  • 22. Data passing with JSON We’d use JSON to pass data to the client when We’re not rendering HTML (e.g. forms, APIs) There’s no other option Bandwidth is expensive Business logic is in the browser
  • 23. Global events One event to rule them all and in the browser bind them
  • 24. Global Events We have bits of HTML loaded asynchronously We already initialized event handles on replaced HTML We want to avoid re-binding event handles with each DOM update
  • 25. Global Events function globalClickHandler(e){ var tgt = $(e.target); do { tag = tgt.get('tag'); if (tag === 'a') { /** do something with link **/} tgt = tgt.getParent(); } while (tag !== 'body'); } document.addEvent(‘click’,globalClickHandler);
  • 26. Global Events We can use the same principle to any other event we want to handle globally We can handle form submission for example Keyboard events Form widgets events
  • 27. Global Events Issues to remember: We have some redundant DOM traversal We should strive to unbind events on unload Too much is no good (don’t over do it)
  • 29. Dependency Management Three approaches Brute and Hungry Requires Script tags
  • 30. Dependency Management Brute and Hungry We load everything when page loads We need to ensure things are packed nicely Jammit or Sprockets Large file limitations (caching, parsing, network) Change in one file forces full cache purge
  • 31. Dependency Management Requires Use a JS dependency library (require.js, head.js) script-ready support load only when needed requires a bit more logic to ensure things run after requires
  • 32. Dependency Management Script tags Fetch JS script tags with HTML Add to DOM once Binds view and JS (good or bad?) Readiness and requiring management needed
  • 33. Dependency Management Brute and Hungry - Small JS apps / non-mobile apps Requires / Script tags - Larger / more complex apps Requires are probably the best solution out there Flexible Functional and Intuitive Penalties are “less” severe
  • 34. Initialization and Execution Executing things without breaking your neck
  • 35. Initialization and execution Our code needs to run at certain points or respond to certain user interactions. How do we know when to initialize and execute the relevant bits of code?
  • 36. Initialization and execution We initialize our application’s entry point module on DOM ready If we’re using requires, we can initialize required modules when they’re required
  • 37. Initialization and execution We have a global handler for async requests We can execute response callbacks based on request URL We can return a bit of Javascript with each response that will be executed when the content is rendered
  • 38. Initialization and execution Finally, we can use an Initializer pattern to call various modules based on some convention: We need module construction and destruction We know what action was performed on the server (e.g. controller name and action name)
  • 39. Initialization and execution var Initializer = { last_action:null, init:function(action){ if(this.last_action && typeof(this.Destructors[this.last_action]) === ‘function’){ this.Destructors[this.last_action](); } if(typeof(this.Constructors[action]) === ‘function’){ this.Constructors[action](); } this.last_action = action; } };
  • 40. Initialization and execution Initializer.Constructors = {}; Initializer.Destructors = {}; /** Somewhere in a module **/ Initializer.Constructors.Gallery = function(){....} Initializer.Destructors.Gallery = function(){....}
  • 41. Initialization and execution /** Our global request handler **/ var Request = { get:function(url){ var xhr = new Request({ url:url, onSuccess:function(response){ // render response here Initializer.init(url.split(‘/’)[1]); } }); xhr.get(); } }
  • 42. Handling forms Handle GET and POST requests separately Form validation is the server’s job!!! The client should assist the user to fill correct values Use server-side validation errors in the client Rely on HTTP error statuses to handle success / failure
  • 43. Handling forms You can have a global form handler, similar to your global request handler Async responses should be: JSON when we check success / failure HTML when we render something after submission Define a coherent API to pass data from server to client on form submission
  • 44. Final thoughts We didn’t talk about Performance, MVC, Couch Apps, templates Do what’s right based on your requirements Learn a goddamn server-side framework
  • 45. Final thoughts Design for simplicity Don’t repeat yourself and don’t reinvent the wheel Start small and grow larger (modules anyone?) Define developer-friendly conventions and follow them

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n