Scherer | Hands-On JavaScript High Performance | E-Book | www2.sack.de
E-Book

E-Book, Englisch, 376 Seiten

Scherer Hands-On JavaScript High Performance

Build faster web apps using Node.js, Svelte.js, and WebAssembly
1. Auflage 2024
ISBN: 978-1-83882-586-7
Verlag: De Gruyter
Format: EPUB
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)

Build faster web apps using Node.js, Svelte.js, and WebAssembly

E-Book, Englisch, 376 Seiten

ISBN: 978-1-83882-586-7
Verlag: De Gruyter
Format: EPUB
Kopierschutz: Adobe DRM (»Systemvoraussetzungen)



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


Discover effective techniques for accessing DOM, minimizing painting, and using a V8 engine to optimize JavaScript
Understand what makes the web tick and create apps that look and feel like native desktop applications
Explore modern JavaScript frameworks like Svelte.js for building next-gen web apps



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


Explore Vanilla JavaScript for optimizing the DOM, classes, and modules, and querying with jQuery
Understand immutable and mutable code and develop faster web apps
Delve into Svelte.js and use it to build a complete real-time Todo app
Build apps to work offline by caching calls using service workers
Write C++ native code and call the WebAssembly module with JavaScript to run it on a browser
Implement CircleCI for continuous integration in deploying your web apps



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.

Scherer Hands-On JavaScript High Performance jetzt bestellen!

Autoren/Hrsg.


Weitere Infos & Material


Table of Contents - Tools for High Performance on the Web
- Immutability versus Mutability - The Balance between Safety and Speed
- Vanilla Land - Looking at the Modern Web
- Practical Example - A Look at Svelte and Being Vanilla
- Switching Contexts - No DOM, Different Vanilla
- Message Passing - Learning about the Different Types
- Streams - Understanding Streams and Non-Blocking I/O

- Data Formats - Looking at Different Data Types Other Than JSON
- Practical Example - Building a Static Server
- Workers - Learning about Dedicated and Shared Workers
- Service Workers - Caching and Making Things Faster
- Building and Deploying a Full Web Application
- WebAssembly - A Brief Look into Native Code on the Web


Chrome – an in-depth look at the Performance tab


As stated before, except for a select few tools inside Firefox, Chrome has become widely ubiquitous as the browser of choice for users and developers. For developers, this can be in large part thanks to its wonderful developer tools. The following sections are going to take a look at three critical tools that are important to any developer when designing web applications. We will start with the performance tool.

This tool allows us to run performance tests while our application is running. This is great if we want to see how our application behaves when certain things are done. For example, we can profile our application's launch state and see where possible bottlenecks are located. Or, when user interaction happens, such as a submit on a form, we can see the call hierarchy that we go through to post the information and return it back to the user. On top of this, it can even help profile code when we use a web worker and how the data transfer works between our application contexts.

Following is a screenshot of the Performance tab from the latest version of Chrome at the time of writing:

There are a couple of sections that are of interest. First, the bar below our developer tool tabs is our main toolbar. The left two buttons are probably the most important, the record and the record on reload tools. These will allow us to profile our application and see what happens at critical junctures in our code. After these come selection tools to grab profiles that you may have run before.

Next up are two options that I usually have turned on at all times:

  • First, the screenshot capability will grab screenshots for us when it sees something critical happening with the application, such as memory growth or a new document being added.
  • The next option is the memory profiler. It will tell us how much memory is being consumed at that time.

Finally, there is the delete action. As many would surmise, this deletes the profile that you are currently on.

Let's do a test run on a simple test application. Grab the chrome_performance.html file from the repository. This file showcases a standard Todo application, but it is written with a very basic templating system and no libraries. No libraries will become a standard throughout this book.

If we run this application and run a performance test from reload, we should get something that looks like the following:

The page should be almost instant to load, but we still get some useful information here. Going from top to bottom, we get the following information:

  • A timeline of pictures, along with graphing for FPS, CPU usage, network usage, and heap usage.
  • A line graph of different statistics, such as JavaScript heap usage, the number of documents, the number of document nodes, the number of listeners, and the GPU memory that we are utilizing.
  • Finally, we get a tabbed section that gives us all of the information about timings and a breakdown of where the time is allocated.
Make sure you let the profiler run its course. It should automatically shut down after all operations are done on the page. This should ensure that you are getting as close to the correct information as possible on how your application is doing. The profiler may have to be run a couple of times to get an accurate picture also. The internal garbage collector is trying to hold onto some objects so that it can reuse them later, so getting an accurate picture means seeing what the low point is since that is most likely where the application baseline is following Garbage Collection (GC). A good indicator of this is seeing a major GC and/or a DOM GC. This means we are starting afresh again.

In this basic example, we can see that most of the time was spent in the HTML. If we open this up, we will then see that evaluating our script took the majority of that time. Since most of our time was spent in evaluating the script and inserting our templated Todo application into the DOM, let's see what the statistics would look like if we did not have this behavior.

Comment out everything except for our basic tags, such as the html, head, and body tags. There are a few interesting elements regarding this run. First, the number of documents should have stayed the same or decreased. This will be touched upon later. Second, the number of nodes decreased dramatically and likely went down to around 12. Our JavaScript heap went down a little bit, and the number of listeners went down significantly.

Let's bring a single div tag back in. The number of documents, heap space, and listeners stayed the same, but the number of nodes increased again. Let's add in another div element and see how that affects the number of nodes. It should increase by four. One last time, let's add in another div element. Again, we should notice an increase of four DOM nodes being added. This gives us a bit of a clue into how the DOM is running and how we can make sure our profiling is correct.

First, the number of nodes is not directly equal to the number of DOM elements that are on the screen. DOM nodes are made up of several underlying basic nodes. As an example, if we add an element such as an input element, we may notice that the number of nodes increases by more than four. Second, the number of documents that are available is almost always going to be higher than a single document.

While some of this behavior can be attributed to bugs in the profiler, it also showcases the fact that there are things happening behind the scenes that are not available to the developer. When we touch on the Memory tab and look at call hierarchies, we will see how internal systems are creating and destroying nodes that a developer does not have full control of, along with documents that are invisible to the developer but are optimizations for the browser.

Let's add in our code block again and get back to what the original document was. If need be, go ahead and revert the Git branch (if this was pulled down from the repository) and run the profiler again. We specifically want to look at the Call Tree tab and the Parse HTML dropdown. There should be a hierarchy that looks something like the following: Parse HTML > Evaluate Script > (anonymous) > runTemplate > runTemplate.

Let's change the code and turn our inner for loop into an array map function like this:

const tempFun = runTemplate.bind(null, loopTemp);
loopEls = data.items.map(tempFun);

Comment out both the loopEls array initialization and also the for loop. Run the profiler again and let's take a look at what this call stack looks like. We will notice that it is still profiling the runTemplate function as itself even though we bound it to a new function called tempFun. This is another piece that we have to keep in mind when we are looking at the call hierarchy. We may bind, call, or apply functions, but the development tools will still try to maintain the original definition of the function.

Finally, let's add a lot of items to our data list and see how this affects our profiling. Put the following code below the data section:

for(let i = 0; i < 10000; i++) {
data.items.push({text : `Another item ${i}`});
}

We should now get a bit of a different picture than what we had before:

  • First, where our time was close to being evenly split between layout by the GPU and the evaluation of our script, it now looks like we are spending most of our time running the layout engine. This makes sense since we are forcing the DOM to figure out the layout for each item when it gets added at the end of our script.
  • Second, the Evaluate Script section should now contain quite a few more pieces than the simple call hierarchy that we saw before.
  • We will also start to see different parts of the function being registered in the profiler. What this shows is that if something is below a certain threshold (it really depends on the machine and even the build of Chrome), it will not show that the function was considered important enough to be profiled.

Garbage collection is the process of our environment cleaning up unused items that we are no longer using. Since JavaScript is a memory-managed environment, meaning developers are not allocating/deallocating memory themselves like in languages such as C++ and Rust, we have a program that does this for us. V8, in particular, has two GCs, a minor GC called Scavenger, and a major one called Mark-Compact.

The scavenger goes through newly allocated objects and sees whether there are any objects that are ready to be cleaned up. Most of the time, our code is going to be written to use a lot of temporary variables for a short time span. This means that they are not going to be needed within a couple of statements of the variables being initialized. Take the following piece of code:

const markedEls = [];
for(let i = 0; i < 10000; i++) {
const obj = els[i];
if( obj.marked ) {
markedEls.push(Object.assign({}, obj));
}
}

In this hypothetical example, we want to get objects and clone them if they are marked for some procedure. We gather the ones that we want and the rest are now unused. The scavenger would notice a couple of things. First, it would seem that we are no longer using the old list, so it would automatically collect this memory. Second, it would notice that we have a...


Scherer Justin :

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. Justin has led development teams that utilize JavaScript on the web and on the server. He currently works for a large financial institution where he is leading the charge on developing highly performant front-end and middleware using JavaScript. On his off time, he has a handful of hobbies: playing the piano, going to concerts, repairing watches, reading, and spending time with his wife. His mind is constantly wandering to new areas where technology, especially web technology could prove useful.



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.