Mastering JavaScript Single Page Application Development An in-depth guide to exploring the design, architecture, and techniques behind building sophisticated, scalable, and maintainable single-page applications in JavaScript Philip Klauzinski John Moore BIRMINGHAM - MUMBAI Mastering JavaScript Single Page Application Development Copyright © 2016 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: October 2016 Production reference: 1241016 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-164-0 www.packtpub.com Credits Authors Copy Editor Philip Klauzinski Safis Editing John Moore Reviewers Project Coordinator Ciro Artigot Ritika Manoj Commissioning Editor Proofreader Wilson D'souza Safis Editing Acquisition Editor Indexer Reshma Raman Rekha Nair Content Development Editor Graphics Divij Kotian Jason Monteiro Technical Editor Production Coordinator Sachit Bedi Aparna Bhagat About the Authors Philip Klauzinski is a senior frontend developer specializing in JavaScript Single Page Application (SPA) development. He has over 20 years of experience in web design and web development and is a leading expert in web application development, client-side JavaScript, and Search Engine Optimization (SEO). Philip has worked as a frontend developer across multiple industries, including consumer e-commerce, business-to-business e-commerce, big data, Web hosting, direct marketing, domain name services (DNS), and manufacturing. I would like to thank my Mom and Dad for always stressing the importance of education in my life, not just institutional education, but more importantly, the pursuance of self- education. My own interest in technology and software from a young age has driven my subsequent, self-taught approach to my career. As a result, I love what I do for a living, and I have been able to shape my professional life around the things in which I am truly interested. I am inherently driven to learn more every day, and I believe that is what has led to my success. Thank you, Mom and Dad! John Moore has been working in web development for 20 years. He is an industry expert in JavaScript and HTML5. He has developed award-winning web applications and worked and consulted for Digital Equipment Corporation, Ernst & Young, Wachovia Bank, and Fidelity Investments. Having focused his early career on frontend web development, he helped usher in responsive web design and Single Page Applications in his roles in development and architecture. Most recently, he led Full Stack development in JavaScript, serving as CTO of a Maine-based startup company. I would like to thank my wife, Dr. Myra Salapare, and daughters, Mila Moore and Sophia Moore, for all of their support. I would also like to thank Andrea Shiflet, Erin Benner, and Lauren Grousd for their tremendous help. About the Reviewer Ciro Artigot is currently working as an IT manager at ECODES, an Spanish foundation that works for the welfare of all people within the limits of our planet. He has developed websites for over 15 years. He is a Full Stack developer and CMS expert and is addicted to Joomla, He has worked for 10 years in open source GNU projects, mainly in LAMP . For the last few years, he has been investigating and working with SPA in MEAN environments. I would like to thank Pampa, Diego,and Hugo, for giving me the time to review this book, and my parents and brothers, for making it possible for me to devote myself to what I like best—develop www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Table of Contents Preface 1 Chapter 1: Getting Organized with NPM, Bower, and Grunt 7 What is Node Package Manager? 8 Installing Node.js and NPM 8 Configuring your package.json file 9 NPM dependencies 10 Updating your development dependencies 11 Bower 11 Installing Bower 12 Configuring your bower.json file 12 Bower components location and the .bowerrc file 14 Bower dependencies 14 Searching the Bower registry 15 Grunt 16 Installing the Grunt CLI 17 Installing the Grunt task runner 17 Installing Grunt plugins 17 Configuring Grunt 19 Understanding Node.js modules 19 Creating a Gruntfile 20 Defining Grunt task configuration 21 Loading Grunt plugins 22 Running the jshint Grunt task 24 Running the watch Grunt task 25 Defining the default Grunt task 27 Defining custom tasks 27 Summary 29 Chapter 2: Model-View-Whatever 30 The original MVC pattern 30 The Model 31 The View 32 The Controller 33 MVP and MVVM 34 MVP 34 MVVM 35 Summarizing the differences between MVC, MVP, and MVVM 36 VIPER and other variations of MVW 36 VIPER 36 Other variations of MVW 37 AngularJS and MVW 38 A brief history of AngularJS 38 AngularJS components 39 Template 39 Directives 39 Model 40 Scope 40 Expressions 40 Compiler 41 Filter 41 View 41 Data binding 41 Controller 42 Dependency injection 42 Injector 43 Module 43 Service 43 Using the MVW pattern in an SPA 44 Building a simple JavaScript SPA 44 Creating the Model 45 Creating the View 45 Setting up frontend assets 46 Compiling web templates 46 Precompiling web templates 46 Handling server HTTP requests 47 Creating the SPA layout 47 Serving the SPA 48 Overview of a simple JavaScript SPA 49 Summary 50 Chapter 3: SPA Essentials – Creating the Ideal Application Environment 51 The JSON data format 51 Other data formats 53 XML 53 YAML 54 BSON 54 Why does JSON reign supreme? 55 The differences between SQL and NoSQL databases 55 NoSQL data typing 56 Relational data typing 56 ACID transactions 57 Atomicity 57 [ ii ] Consistency 57 Isolation 58 Durability 58 MongoDB and ACID 58 Write-ahead logging with MongoDB 58 When to use SQL versus NoSQL databases 59 Scalability 59 Horizontal scaling 59 Big Data 59 Operational Big Data 60 Analytical Big Data 60 Overall considerations 61 Methods of presenting an SPA container 61 How to define your SPA container 62 Partial page container 62 Full page container 62 How to load your SPA container 63 Loading on user interaction 63 Login page transition 63 Loading based on the DOMContentLoaded event 64 Loading based on the document readystatechange event 65 Loading directly from the document.body 65 Using the script tag async attribute 67 Using the script tag defer attribute 67 Managing layouts 68 Static layouts 68 Dynamic layouts 69 Installing Express 69 Setting up a basic server with Express 70 Basic routing with Express 70 Running a server with Express 71 Loading static assets with Express 71 Dynamic routing with Express 72 Summary 73 Chapter 4: REST is Best – Interacting with the Server Side of Your App 74 Understanding the fundamentals of REST 75 Understanding an architectural style versus a protocol 75 Architectural style 75 Protocol 76 Transport layer protocols 76 Application layer protocols 76 Using HTTP as a transfer protocol for REST 77 The constraints of REST 78 Client-server 78 [ iii ]