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
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.
Download PDF
Download EPUB
.epub
digital book format is ideal for reading ebooks on phones, tablets, and e-readers.