Facebook Pixel
Searching...
English
EnglishEnglish
EspañolSpanish
简体中文Chinese
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
Bahasa IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
High Performance JavaScript

High Performance JavaScript

Build Faster Web Application Interfaces
by Nicholas C. Zakas 2010 232 pages
4.11
500+ ratings
Listen

Key Takeaways

1. Load JavaScript efficiently to reduce HTTP requests and improve page speed

Reduce the number of HTTP requests required to render the page.

Combine and position scripts. Merge multiple JavaScript files into a single file to minimize HTTP requests. Place script tags at the bottom of the HTML body to allow the page to load visually before executing scripts. Use asynchronous loading techniques like dynamic script insertion or the defer attribute when possible.

Minify and compress. Use tools like the YUI Compressor to remove unnecessary characters and whitespace from JavaScript files. Enable gzip compression on your web server to further reduce file sizes. Consider using a Content Delivery Network (CDN) to serve static assets, including JavaScript files, from geographically distributed servers for faster delivery.

Implement caching strategies. Set appropriate cache headers for JavaScript files to allow browsers to store them locally. Use versioning or timestamps in file names to force updates when necessary. For mobile devices with limited caching capabilities, consider using HTML5 application cache or client-side storage mechanisms.

2. Optimize data access and scope management for faster execution

Local variables are always the fastest to access inside of a function, whereas global variables will generally be the slowest.

Minimize scope chain traversal. Store frequently accessed out-of-scope variables in local variables. Avoid using the with statement and eval(), as they can extend the scope chain and slow down execution. Use closures judiciously, as they maintain references to their outer scope and can impact memory usage.

Optimize object and array access. Use dot notation instead of bracket notation when accessing object properties with known, valid identifiers. Cache the length of arrays in for loops to avoid repeated property lookups. Consider using plain objects or arrays instead of more complex data structures when simple key-value storage is sufficient.

Leverage literal notation. Use object and array literals instead of their constructor counterparts (e.g., {} instead of new Object()). This not only improves readability but can also be faster in many JavaScript engines.

3. Minimize DOM manipulation to enhance performance

DOM access and manipulation are an important part of modern web applications. But every time you cross the bridge from ECMAScript to DOM-land, it comes at a cost.

Batch DOM operations. Minimize direct DOM manipulation by making changes to a document fragment or cloned node before updating the live DOM. This reduces the number of reflows and repaints, which are computationally expensive.

Use efficient selectors. Leverage native DOM methods like getElementById() and querySelector() instead of more generic methods. When using libraries, ensure they utilize these faster native methods when available. Cache DOM references for elements that are accessed frequently.

Optimize event handling. Implement event delegation by attaching event listeners to parent elements instead of individual child elements. This reduces the number of event listeners and improves performance, especially for dynamically added elements.

4. Implement efficient algorithms and flow control techniques

There are actually just two factors: work done per iteration and number of iterations.

Optimize loops. Minimize the work done in each iteration by moving invariant code outside the loop. Use reverse while loops when possible, as they are often faster than for loops. Consider using array methods like forEach(), map(), and reduce() for cleaner and potentially faster iterations.

Choose appropriate conditionals. Use switch statements instead of long if-else chains when dealing with multiple discrete values. For complex conditions, consider using lookup tables or bitmasks for faster evaluation.

Implement memoization. Cache the results of expensive function calls to avoid redundant calculations. This is especially useful for recursive functions or operations that are called frequently with the same inputs.

5. Choose the right data format for optimal Ajax performance

JSON has several advantages when compared to XML. It is a much smaller format, with less of the overall response size being used as structure and more as data.

Prefer JSON over XML. JSON is more compact and faster to parse than XML. When possible, use JSON-P (JSON with padding) for even faster parsing, especially when dealing with large datasets. For extremely large datasets, consider using custom delimited formats for minimal overhead.

Optimize data transmission. Use GET requests for idempotent operations and POST for larger payloads. Implement proper caching strategies for Ajax responses to reduce unnecessary network requests. Consider using techniques like multipart XHR to bundle multiple resources into a single request.

Handle data efficiently. Parse JSON responses using native methods like JSON.parse() when available. Implement progressive rendering for large datasets to improve perceived performance. Use web workers for time-consuming parsing or processing tasks to keep the UI responsive.

6. Create responsive interfaces by managing the browser UI thread

No JavaScript task should take longer than 100 milliseconds to execute.

Break up long-running tasks. Use setTimeout() or setInterval() to split lengthy operations into smaller chunks, allowing the UI to remain responsive. Consider using Web Workers for CPU-intensive tasks that don't require DOM access.

Optimize event handlers. Debounce or throttle event handlers for frequent events like scrolling or resizing to reduce the number of function calls. Ensure that event handlers complete quickly, especially for user interactions.

Manage animations efficiently. Use requestAnimationFrame() for smoother animations that are synchronized with the browser's rendering cycle. Minimize the number of elements being animated and use CSS transitions or animations when possible for better performance.

7. Leverage build and deployment processes to boost JavaScript performance

Everything that can be done at buildtime should not be done at runtime.

Automate optimizations. Implement a build process using tools like Grunt, Gulp, or Webpack to automate tasks such as concatenation, minification, and compression of JavaScript files. Use source maps to maintain debuggability of minified code.

Implement code splitting. Divide your application into smaller chunks that can be loaded on demand, reducing the initial payload and improving startup time. Use techniques like lazy loading for non-critical resources.

Optimize for production. Remove development-only code, such as logging and debugging statements, in production builds. Implement feature detection instead of browser detection to create more maintainable and performant code across different environments.

8. Utilize profiling tools to identify and resolve performance bottlenecks

Having the right software is essential for identifying bottlenecks in both the loading and running of scripts.

Leverage browser dev tools. Use built-in profilers in browsers like Chrome DevTools, Firefox Developer Tools, and Safari Web Inspector to analyze JavaScript execution time and identify slow functions. Utilize network panels to optimize resource loading and identify bottlenecks in asset delivery.

Implement custom timing. Use the Performance API (window.performance) or custom timing functions to measure specific operations in your code. This allows for more granular performance tracking and optimization.

Monitor real-world performance. Implement Real User Monitoring (RUM) to collect performance data from actual users. This provides insights into how your application performs across different devices and network conditions, helping prioritize optimization efforts.

Last updated:

Review Summary

4.11 out of 5
Average of 500+ ratings from Goodreads and Amazon.

High Performance JavaScript receives mixed reviews, with an average rating of 4.11 out of 5. Many readers praise its detailed insights and practical tips for optimizing JavaScript code. However, some criticize its outdated content, as the book was published in 2010. Positive aspects include thorough explanations of performance techniques, DOM interactions, and regular expressions. Critics note that many practices are now standard and that browser benchmarks are obsolete. Despite its age, some readers still find value in the fundamentals and historical perspective on JavaScript performance optimization.

Your rating:

About the Author

Nicholas C. Zakas is a prominent figure in front-end development, known for his expertise in JavaScript and web technologies. He worked at Yahoo! for nearly five years, contributing to the YUI library and leading front-end development for the Yahoo! homepage. Zakas has authored several influential books on JavaScript, including "Maintainable JavaScript," "Professional JavaScript for Web Developers," and "High Performance JavaScript." His work focuses on best practices in web development, emphasizing progressive enhancement, accessibility, performance, scalability, and maintainability. As a consultant, author, and speaker, Zakas continues to shape the field of front-end development through his contributions to industry knowledge and standards.

Download PDF

To save this High Performance JavaScript summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.41 MB     Pages: 9

Download EPUB

To read this High Performance JavaScript summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 3.16 MB     Pages: 8
0:00
-0:00
1x
Dan
Andrew
Michelle
Lauren
Select Speed
1.0×
+
200 words per minute
Create a free account to unlock:
Bookmarks – save your favorite books
History – revisit books later
Ratings – rate books & see your ratings
Unlock unlimited listening
Your first week's on us!
Today: Get Instant Access
Listen to full summaries of 73,530 books. That's 12,000+ hours of audio!
Day 4: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 7: Your subscription begins
You'll be charged on Nov 28,
cancel anytime before.
Compare Features Free Pro
Read full text summaries
Summaries are free to read for everyone
Listen to summaries
12,000+ hours of audio
Unlimited Bookmarks
Free users are limited to 10
Unlimited History
Free users are limited to 10
What our users say
30,000+ readers
“...I can 10x the number of books I can read...”
“...exceptionally accurate, engaging, and beautifully presented...”
“...better than any amazon review when I'm making a book-buying decision...”
Save 62%
Yearly
$119.88 $44.99/yr
$3.75/mo
Monthly
$9.99/mo
Try Free & Unlock
7 days free, then $44.99/year. Cancel anytime.
Settings
Appearance