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

PPTX
JavaScript : A trending scripting language
PPTX
Slideshare - Magento Imagine - Do You Queue
PPT
PPTX
Html web workers
PPT
JavaScript Introduction
PPTX
Introduction about-ajax-framework
PPTX
jQuery From the Ground Up
PDF
WordPress and Client Side Web Applications WCTO
JavaScript : A trending scripting language
Slideshare - Magento Imagine - Do You Queue
Html web workers
JavaScript Introduction
Introduction about-ajax-framework
jQuery From the Ground Up
WordPress and Client Side Web Applications WCTO

What's hot (20)

PDF
Wordcamp Toronto Presentation
PPTX
ASP.NET MVC and ajax
PPTX
Single Page Applications: Your Browser is the OS!
PPTX
Introduction to ASP.NET MVC
PPT
Web development basics (Part-3)
PPTX
ASP.NET MVC Performance
PPTX
PPT
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
PPTX
Ajax ppt - 32 slides
PPTX
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
PPT
KnockoutJS and MVVM
PPTX
Introduction to ajax
PDF
1 ppt-ajax with-j_query
DOCX
Rails Concept
PDF
Web application intro
PDF
Ember.js for Big Profit
PPTX
Increase automation to rest
PPTX
Optimizing Content Managed Rich JavaScript Apps
PPTX
Better End-to-End Testing with Page Objects Model using Protractor
Wordcamp Toronto Presentation
ASP.NET MVC and ajax
Single Page Applications: Your Browser is the OS!
Introduction to ASP.NET MVC
Web development basics (Part-3)
ASP.NET MVC Performance
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
Ajax ppt - 32 slides
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
KnockoutJS and MVVM
Introduction to ajax
1 ppt-ajax with-j_query
Rails Concept
Web application intro
Ember.js for Big Profit
Increase automation to rest
Optimizing Content Managed Rich JavaScript Apps
Better End-to-End Testing with Page Objects Model using Protractor
Ad

Viewers also liked (8)

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

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

PPT
Using Ajax In Domino Web Applications
PDF
Isomorphic JavaScript: #DevBeat Master Class
PDF
Intro to mobile web application development
PDF
Beginning MEAN Stack
PPTX
Reactive application using meteor
PDF
react hook and wesite making structure ppt
PDF
Advanced web application architecture - Talk
PDF
Having Fun Building Web Applications (Day 1 Slides)
PDF
SocketStream
PDF
React loadable
PPT
Html JavaScript and CSS
PPTX
Intro to AngularJs
PDF
Intro to ember.js
PDF
Ionic framework one day training
PDF
Full Stack React Workshop [CSSC x GDSC]
PPTX
Web Development Today
ODP
An Overview of Node.js
PPTX
React js - The Core Concepts
Using Ajax In Domino Web Applications
Isomorphic JavaScript: #DevBeat Master Class
Intro to mobile web application development
Beginning MEAN Stack
Reactive application using meteor
react hook and wesite making structure ppt
Advanced web application architecture - Talk
Having Fun Building Web Applications (Day 1 Slides)
SocketStream
React loadable
Html JavaScript and CSS
Intro to AngularJs
Intro to ember.js
Ionic framework one day training
Full Stack React Workshop [CSSC x GDSC]
Web Development Today
An Overview of Node.js
React js - The Core Concepts

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Machine learning based COVID-19 study performance prediction
NewMind AI Weekly Chronicles - August'25 Week I
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Monthly Chronicles - July 2025
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation_ Review paper, used for researhc scholars
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
MYSQL Presentation for SQL database connectivity
Machine learning based COVID-19 study performance prediction

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