Hands-On Javascript High Performance
Total Page:16
File Type:pdf, Size:1020Kb
Hands-On JavaScript High Performance Build faster web apps using Node.js, Svelte.js, and WebAssembly Justin Scherer BIRMINGHAM - MUMBAI Hands-On JavaScript High Performance 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 Ramchandani Acquisition Editor: Ashitosh Gupta Content Development Editor: Keagan Carneiro Senior Editor: Hayden Edwards Technical Editor: Jane Dsouza Copy Editor: Safis Editing Project Coordinator: Manthan Patel Proofreader: Safis Editing Indexer: Tejal Daruwale Soni Production 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 To my mother, Kristi, and to my father, Jerry, for their love, determination, and sacrifice throughout life. To my wife, Vlasta, for being my loving spouse and partner in life. – Justin Scherer 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. Why subscribe? 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. Contributors About the author 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. I would first like to thank my wife for being the wonderful person she is. If it were not for her, I would still be wondering whether I could even write a book in the first place. She has always pushed me to be the best person, even when she does not realize she is doing it. I would also like to thank my mom for always being the most wonderful person I have ever known and for always being the biggest supporter no matter what I decided to do. I would like to thank my dad for always being one step ahead of me and keeping me on my toes; he is my role model and I strive to be as good of a man as he is. Finally, I would like to thank my brother. While he may not realize the impact he has had on me, he has always shown me what it means to work hard and to achieve your goals. About the reviewer Jean-Sébastien Goupil 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. Packt is searching for authors like you 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. Table of Contents Preface 1 Chapter 1: Tools for High Performance on the Web 7 Technical requirements 8 DevTools for different environments 8 Edge 8 Safari 9 Firefox 10 Chrome 12 Chrome – an in-depth look at the Performance tab 14 Chrome – an in-depth look at the Memory tab 19 Chrome – an in-depth look at the Rendering tab 23 jsPerf and benchmarking 29 Summary 34 Chapter 2: Immutability versus Mutability - The Balance between Safety and Speed 35 Technical requirements 35 The current fascination with immutability 36 A dive into Redux 37 Immutable.js 44 Writing safe mutable code 47 Resource allocation is initialization (RAII) 53 Functional style programming 58 Lazy evaluation 58 Tail-end recursion optimization 61 Currying 63 Summary 66 Chapter 3: Vanilla Land - Looking at the Modern Web 67 Technical requirements 68 A dive into modern JavaScript 68 Let/const and block scoping 68 Arrow functions 70 Collection types 71 Reflection and proxies 77 Other notable changes 80 Spread operator 80 Destructuring 81 Power operator 81 Table of Contents Parameter defaults 81 String templates 82 Typed arrays 83 BigInt 83 Internationalization 84 Understanding classes and modules 84 Other notable features 87 Modules 91 Working with the DOM 94 Query selector 94 Document fragments 95 Shadow DOM 96 Web components 97 Templates 100 Understanding the Fetch API 101 Promises 103 Back to fetch 105 Stopping fetch requests 107 Summary 108 Chapter 4: Practical Example - A Look at Svelte and Being Vanilla 109 Technical requirements 110 A framework for pure speed 110 Build the basics – a Todo application 114 Getting fancier – a basic weather application 122 Summary 131 Chapter 5: Switching Contexts - No DOM, Different Vanilla 132 Technical requirements 133 Getting Node.js 133 Overview of the package.json file 135 Understanding the DOM-less world 138 A first look at streams 138 A high-level look at modules 142 fs module 142 net module 144 http module 147 Debugging and inspecting code 149 Summary 152 Chapter 6: Message Passing - Learning about the Different Types 153 Technical requirements 154 Local communication using the net module 154 Understanding the cluster module 162 Common pitfalls for new developers 166 Utilizing the network 167 [ ii ] Table of Contents TCP/UDP 168 HTTP/2 173 A quick glance at HTTP/3 176 The QUIC protocol 177 A look at node-quic 177 Summary 179 Chapter 7: Streams - Understanding Streams and Non-Blocking I/O 180 Technical requirements 181 Getting started with streams 181 Building a custom Readable stream 185 Understanding the Readable stream interface 187 Implementing the Readable stream 189 Building a Writable stream 192 Understanding the Writable stream interface 192 Implementing the Writable stream 193 Implementing a Duplex stream 195 Implementing a Transform stream 199 Understanding the Transform stream interface 200 Implementing a Transform stream 200 Using generators with streams 202 Summary 204 Chapter 8: Data Formats - Looking at Different Data Types Other Than JSON 205 Technical requirements 206 Using JSON 207 Implementing the encoder 209 Implementing the decoder 213 A look at data formats 220 Summary 223 Chapter 9: Practical Example - Building a Static Server 224 Technical requirements 224 Understanding static content 225 Starting our application 225 Setting up our templating system 228 Setting up our server 239 Adding caching and clustering 246 Summary 250 Chapter 10: Workers - Learning about Dedicated and Shared Workers 251 Technical requirements 252 Offloading work to a dedicated worker 252 Moving data in our application 255 [ iii ] Table of Contents Sending binary data in the browser 260 Sharing data and workers 263 Building a simple shared cache 270 Summary 276 Chapter 11: Service Workers - Caching and Making Things Faster 277 Technical requirements 277 Understanding the ServiceWorker 278 Caching pages and templates for offline use 283 Saving requests