32,36 €
An example-driven guide covering modern web app development techniques and emerging technologies such as WebAssembly, Service Workers, and Svelte.js to build faster, secure, and scalable apps
Key Features
Book Description
High-performance web development is all about cutting through the complexities in different layers of a web app and building services and APIs that improve the speed and performance of your apps on the browser. With emerging web technologies, building scalable websites and sustainable web apps is smoother than ever.
This book starts by taking you through the web frontend, popular web development practices, and the latest version of ES and JavaScript. You'll work with Node.js and learn how to build web apps without a framework. The book consists of three hands-on examples that help you understand JavaScript applications at both the server-side and the client-side using Node.js and Svelte.js. Each chapter covers modern techniques such as DOM manipulation and V8 engine optimization to strengthen your understanding of the web. Finally, you'll delve into advanced topics such as CI/CD and how you can harness their capabilities to speed up your web development dramatically.
By the end of this web development book, you'll have understood how the JavaScript landscape has evolved, not just for the frontend but also for the backend, and be ready to use new tools and techniques to solve common web problems.
What you will learn
Who this book is for
This JavaScript book is for web developers, C/C++ programmers, and anyone who wants to build robust web applications using advanced web technologies. This book assumes a good grasp of Vanilla JavaScript and an understanding of web development tools, such as Chrome Developer tools or Mozilla's developer tools.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 532
Veröffentlichungsjahr: 2020
Copyright © 2020 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 author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor:Pavan RamchandaniAcquisition Editor:Ashitosh GuptaContent Development Editor:Keagan CarneiroSenior Editor: Hayden EdwardsTechnical Editor:Jane DsouzaCopy Editor: Safis EditingProject Coordinator:Manthan PatelProofreader: Safis EditingIndexer:Tejal Daruwale SoniProduction Designer: Alishon Mendonsa
First published: February 2020
Production reference: 1280220
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-109-8
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
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.packt.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.packt.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.
Justin Scherer has been professionally developing JavaScript applications for over 10 years. On top of this, he has worked in a variety of fields, ranging from embedded systems to high-performance cluster applications. Utilizing JavaScript to cluster simulation models, write RFID tracking systems, and even to hook Fortran code together, Justin brought JavaScript to Argonne National Laboratory as a way of quickly prototyping and building out ideas.
Justin then went on to work for an e-learning start-up and lead the frontend development team. He currently works for a large financial institution, where he is leading the charge on developing a highly performant frontend and middleware through the use of JavaScript.
During his time off, he has a handful of hobbies, including but not limited to playing the piano, going to concerts, repairing watches, reading, and spending time with his wife. He enjoys his time with his wife and their cat and dog. His mind is constantly wandering to new areas where technology, especially web technology, could prove useful.
Jean-SébastienGoupil is a web developer with more than 15 years of experience. He previously worked for Microsoft and is now a web architect consultant for his own company, working with new clients on web products. He champions quality and consistency at every opportunity and is driven to help others through teaching and blogging.
In his free time, he codes barcode software. He loves sports, hiking, canoeing, crabbing, and chatting about technology.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On JavaScript High Performance
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Tools for High Performance on the Web
Technical requirements
DevTools for different environments
Edge
Safari
Firefox
Chrome
Chrome – an in-depth look at the Performance tab
Chrome – an in-depth look at the Memory tab
Chrome – an in-depth look at the Rendering tab
jsPerf and benchmarking
Summary
Immutability versus Mutability - The Balance between Safety and Speed
Technical requirements
The current fascination with immutability
A dive into Redux
Immutable.js
Writing safe mutable code
Resource allocation is initialization (RAII)
Functional style programming
Lazy evaluation
Tail-end recursion optimization
Currying
Summary
Vanilla Land - Looking at the Modern Web
Technical requirements
A dive into modern JavaScript
Let/const and block scoping
Arrow functions
Collection types
Reflection and proxies
Other notable changes
Spread operator
Destructuring
Power operator
Parameter defaults
String templates
Typed arrays
BigInt
Internationalization
Understanding classes and modules
Other notable features
Modules
Working with the DOM
Query selector
Document fragments
Shadow DOM
Web components
Templates
Understanding the Fetch API
Promises
Back to fetch
Stopping fetch requests
Summary
Practical Example - A Look at Svelte and Being Vanilla
Technical requirements
A framework for pure speed
Build the basics – a Todo application
Getting fancier – a basic weather application
Summary
Switching Contexts - No DOM, Different Vanilla
Technical requirements
Getting Node.js
Overview of the package.json file
Understanding the DOM-less world
A first look at streams
A high-level look at modules
fs module
net module
http module
Debugging and inspecting code
Summary
Message Passing - Learning about the Different Types
Technical requirements
Local communication using the net module
Understanding the cluster module
Common pitfalls for new developers
Utilizing the network
TCP/UDP
HTTP/2
A quick glance at HTTP/3
The QUIC protocol
A look at node-quic
Summary
Streams - Understanding Streams and Non-Blocking I/O
Technical requirements
Getting started with streams
Building a custom Readable stream
Understanding the Readable stream interface
Implementing the Readable stream
Building a Writable stream
Understanding the Writable stream interface
Implementing the Writable stream
Implementing a Duplex stream
Implementing a Transform stream
Understanding the Transform stream interface
Implementing a Transform stream
Using generators with streams
Summary
Data Formats - Looking at Different Data Types Other Than JSON
Technical requirements
Using JSON
Implementing the encoder
Implementing the decoder
A look at data formats
Summary
Practical Example - Building a Static Server
Technical requirements
Understanding static content
Starting our application
Setting up our templating system
Setting up our server
Adding caching and clustering
Summary
Workers - Learning about Dedicated and Shared Workers
Technical requirements
Offloading work to a dedicated worker
Moving data in our application
Sending binary data in the browser
Sharing data and workers
Building a simple shared cache
Summary
Service Workers - Caching and Making Things Faster
Technical requirements
Understanding the ServiceWorker
Caching pages and templates for offline use
Saving requests for later
Summary
Building and Deploying a Full Web Application
Technical requirements
Understanding Rollup
Building our static server into a single distributable
Adding other file types to our distribution
Bringing rollup into Node.js commands
Integrating into CircleCI
Adding our build steps
Deploying our build
Summary
WebAssembly - A Brief Look into Native Code on the Web
Technical requirements 
Understanding WebAssembly
Understanding a program
Setting up our environment
Writing WebAssembly modules
Sharing memory between WebAssembly and JavaScript
Writing FizzBuzz in WebAssembly
Writing C/C++ for the web
Writing a hamming code generator
A look at SQLite in the browser
Summary
Further reading
Other Books You May Enjoy
Leave a review - let other readers know what you think
Much of today's web environment has changed dramatically – not only in terms of creating web applications but also when it comes to creating server-side applications. A frontend ecosystem that was dominated by jQuery and CSS frameworks such as Bootstrap has been replaced with reactive, fully fledged applications that could be mistaken for an application running on the desktop.
The language we write these applications in has also changed in a dramatic fashion. What was once a mess of var and scope issues has turned into a fast and easy-to-program language. JavaScript has not only changed the way we write our frontend, it has also changed the backend programming experience.
We are now able to write server-side applications in the language that we write our frontend in. JavaScript has also modernized, and possibly even popularized, the event-driven system with Node.js. We can now write code for both our frontend and backend in JavaScript and possibly even share the JavaScript files we generate between the two.
However, while the application landscape has evolved and many people have moved onto modern frameworks, such as React and Vue.js for the frontend and Express and Sails for the backend, many of these developers do not understand the inner workings. While this showcases just how simple it is to enter into the ecosystem, it also showcases how easy it is to not understand how to optimize our code bases.
This book focuses on teaching highly performant JavaScript. This not only means fast execution speeds, but also a lower memory footprint. This means that any frontend system will get to the user faster, and we will be able to start our applications that much faster. On top of this, we have many new technologies that have moved the web forward, such as Web Workers.
This book is for those who are interested in all the latest features of the modern web. On top of this, it's also for those with an interest in reducing memory costs while increasing speed. People who are interested in how a computer works and even how a JavaScript compiler works will be interested in the contents of this book. Finally, for those who are interested in WebAssembly but do not know where to start, this is a good jumping-off point in learning the essentials.
Chapter 1, Tools for High Performance on the Web, will cover the various browsers that our applications can run on. We will also take a look at the various tools that help us to debug, profile, and even run ad hoc code to test the functionality of our JavaScript.
Chapter 2, Immutability versus Mutability – The Balance between Safety and Speed, will take a look at the concepts of mutable/immutable state. We will cover when and where to use each. On top of this, we will cover how to create the illusion of immutability while having a mutable data structure.
Chapter 3, Vanilla Land – Looking at the Modern Web, will take a look at how far JavaScript has come and all of the new and notable features up to ECMAScript 2020. On top of this, we will look at various advanced features, such as currying and writing in a functional manner.
Chapter 4, Practical Example – A Look at Svelte and Being Vanilla, will cover a fairly new framework called Svelte. It will go over this compile to Vanilla JavaScript framework and explore how it achieves lightning-fast results with an intuitive framework.
Chapter 5, Switching Contexts – No DOM, Different Vanilla, will cover the low-level Node.js work. This means taking a look at the various modules available to us. We will also take a look at how we can achieve amazing results with no extra libraries.
Chapter 6, Message Passing – Learning about the Different Types, will take a look at different ways to talk among different processes. We will cover unnamed pipes, named pipes, sockets, and transmission via TCP/UDP. We will also take a look at HTTP/2 and briefly look at HTTP/3.
Chapter 7, Streams – Understanding Stream and Non-Blocking I/O, will cover the Stream API and how to utilize it. We will cover each type of stream and the use cases for each. On top of this, we will implement some practical streams that, with some modification, could be used in other projects.
Chapter 8, Data Formats – Looking at Different Data Types Other Than JSON, will look into schema and schema-less data types. We will look into implementing a data format and then see popular data formats in action.
Chapter 9, Practical Example – Building a Static Server, will take the previous four chapters and apply these concepts and build a static site generator. While it may not be as powerful as GatsbyJS, it will have most of the features we expect from a static site generator.
Chapter 10, Workers – Learning about Dedicated and Shared Workers, will move back to the frontend and take a look at two of the web worker types. We will utilize these to process data from the main thread. On top of this, we will take a look at how we can talk among our workers and the main process.
Chapter 11, Service Workers – Caching and Making Things Faster, will look at the service worker and the life cycle of the service worker. On top of this, we will look at practical examples of how to utilize a service worker in a progressive web application.
Chapter 12, Building and Deploying a Full Web Application, will look at continuous integration/continuous deployment (CI/CD) with the tool CircleCI. We will see how we can use it to deploy our web application built in Chapter 9, Practical Example – Building a Static Server, to a server. We will even take a look at adding some security checks to our application before deployment.
Chapter 13, WebAssembly – A Brief Look into Native Code on the Web, will look at this relatively new technology. We will see how to write low-level WebAssembly and how it runs on the web. We will then turn our attention to writing C++ for the browser. Finally, we will take a look at a ported application and the WebAssembly that is behind it.
In general, the requirements to run most of the code are minimal. A computer that is capable of handling Chrome, Node.js, and a C compiler is needed. The C compiler that we will be utilizing near the end of this book will be CMake. These systems should work on all modern operating systems.
For Chrome, having the latest versions will be helpful as we will be utilizing some features that are either in the proposal stage or in ECMAScript 2020. We are using the latest LTS version of Node.js (v12.16.1), and are avoiding the use of Node.js 13 as it won't be promoted to LTS. On top of this, the command-line tool for Windows is not that great, so it is recommended to download Cmder, from https://cmder.net/, to have a Bash-like shell for Windows.
Finally, a modern IDE or editor is needed. We will be utilizing Visual Studio Code throughout this book, but many other alternatives, such as Visual Studio, IntelliJ, Sublime Text 3, and so on, can be used.
Software/hardware covered in the book
Operating system requirements
Svelte.js v3
Windows 10/OSX/Linux
ECMAScript 2020
Windows 10/OSX/Linux
Node.js v12.16.1 LTS
Windows 10/OSX/Linux
WebAssembly
Windows 10/OSX/Linux
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-High-Performance-Web-Development-with-JavaScript. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
JavaScript has become the mainstay language of the web. There is no extra runtime needed, and there is no compilation process required to run an application in JavaScript. Any user can open up a web browser and start typing in the console to learn the language. In addition to this, there have been many advancements in the language along with the Document Object Model (DOM). All of this has led to a rich environment for developers to take and create.
On top of this, we can see the web as a build once, deploy anywhere environment. The code that works on one operating system will work on another. There is some variation that will need to happen if we want to target all browsers, but it can be seen as a develop once, deploy anywhere platform. However, all of this has led to applications that have become bloated, with expensive frameworks and unnecessary polyfills. The necessity for these frameworks can be seen in most job postings, but sometimes we don't need them to create rich applications.
This chapter focuses on the tools that we will use to help us build and profile high-performance web applications. We will take a look at the different modern browsers and their unique contributions. We will then take a deep dive into the Chrome developer tools. Overall, we will learn the following:
The different development tools embedded in each browser
An in depth look at the following
Chrome tools:
The Performance tab
The Memory tab
The Renderer tab
jsPerf and benchmarking code
The following are prerequisites for this chapter:
A web browser, preferably Chrome.
An editor; VS Code is preferred.
Knowledge of JavaScript and some of the DOM APIs.
The relevant code can be found at
https://github.com/PacktPublishing/Hands-On-High-Performance-Web-Development-with-JavaScript/tree/master/Chapter01
.
There are four browsers that are considered modern browsers. These are Edge, Chrome, Firefox, and Safari. These browsers uphold the latest in standards and are being actively developed. We will take a look at how each is developing and some of their unique features.
Microsoft's Edge browser was their take on the modern web. With the EdgeHTML renderer and the Chakra JavaScript engine, it performs well in many benchmarks. While the Chakra engine does have different optimizations for it than Chrome or Firefox, it is an interesting browser to look at from a pure JavaScript perspective.
In terms of features, Edge is light compared to the other browsers. If we need to perform any type of performance testing for it, the best bet is to profile code with jsPerf or others instead of the built-in tools. On top of this, the Chakra engine utilizes different optimization techniques, so what may work with Chrome or Safari may be less optimized for Edge. To get to the developer tools on Windows, we can press F12. This will pull up the usual console dialog, shown as follows:
We will not be going through any interesting features specific to Edge since most, if not all, of the features in their developer tools are the same as those found in other browsers.
Apple's Safari browser is based on the WebKit rendering engine and the JavaScriptCore engine. The WebKit engine is what Chrome's Blink engine is based on, and the JavaScriptCore engine is used in a few places for the OS X operating system. An interesting point regarding Safari is the fact that if we are running Windows or Linux, we will not be able to access it directly.
To get access to Safari, we will need to utilize an online service. BrowserStack or LambdaTest, along with a host of others, can do this job for us. With any of these, we now have access to browsers that we may not otherwise have had. Thanks to LambdaTest, we will utilize their free service to take a brief look at Safari.
Again, we will notice that there is not too much to the Safari browser development tools. All of the same tools are also available in the other browsers and they are usually more powerful in these other browsers. Getting familiar with each of the interfaces can help when debugging in that specific browser, but not a lot of time needs to be dedicated to looking at the browsers that do not have any specific features unique to them.
Google's Chrome browser utilizes the Blink engine and uses the famous V8 JavaScript runtime. This is the same runtime that is used inside Node.js, so getting familiar with the development tools will help us in a lot of ways.
Chrome has been at the forefront of web technologies, just like Firefox. They have been the first to implement various ideas, such as the QUIC protocol, which the HTTP/3 standard is loosely based on. They created the Native Plugin Interface (NaCL) that helped, alongside asm.js, to create the standard for WebAssembly. They have even been pioneers in making web applications start to become more native-like by giving us APIs such as the Bluetooth, Gamepad, and Notifications APIs.
We will be specifically looking at the Lighthouse feature that comes with Chrome. The Lighthouse feature can be accessed from the Audits tab in the Chrome browser. Once we are here, we can set up our audit with a myriad of settings:
First, we can audit our page based on it running from a mobile device or desktop. We can then audit various features of our site.
If we are developing a progressive web application, we may decide that SEO is not needed. On the other hand, if we are developing a marketing site, we could decide that the progressive web app check is not needed. We can simulate a throttled connection.
Finally, we can start off with clean storage. This is especially helpful if our application utilizes caching systems that are built into browsers, such as session storage or local storage.
As an example, let's look at an external site and see how well it stacks up in the audit application. The site we will be looking at is Amazon, located at https://www.amazon.com. The site should be a good example for us to follow. We are going to look at it as a desktop application, without any throttling. If we run the audit, we should get something that looks like the following:
As we can see, the main page does well in performance and best practices, but Chrome is warning us about accessibility and SEO performance. In terms of accessibility, it seems that images do not have alt attributes, which means screen readers are not going to work well. Also, it seems that the developers have tabindexes higher than 0, possibly causing the tab order to not follow the normal page flow.
If we wanted to set up our own system to test, we would need to host our pages locally. There are many great static site hosting solutions (we will be building one later in the book), but if we needed to host content, one of the easiest methods would be to download Node.js and install the static-server module. We will go into depth later on how to get Node.js up and running and how to create our own servers, but for now, this is the best bet.
We have looked at the main modern web browsers that are out there and that we should target. Each of them has its own capabilities and limitations, which means we should be testing our applications on all of them. However, the focus of this book will be the Chrome browser and the developer tools that come with it. Since Node.js is built with the V8 engine, and with many other new browsers being based on the Chromium engine, such as Brave, it would make sense to utilize this. We are going to go into detail regarding three specific features that the Chrome developer tools give us.
