DEV Community

Cover image for Turbocharge Your Web: Mastering Performance JavaScript.πŸš€πŸš€πŸš€
Dharmendra Kumar
Dharmendra Kumar

Posted on

Turbocharge Your Web: Mastering Performance JavaScript.πŸš€πŸš€πŸš€

1. Performance Basics

Real vs. Perceived Performance

  • Real Performance: Actual speed improvements such as smaller file sizes and quicker load times.
  • Perceived Performance: Enhancements that make the website feel faster to the user, like progress indicators and immediate content display.

Example

Show a loading spinner while fetching data to make the user feel like something is happening immediately.

<div id="spinner">Loading...</div>
<div id="content" style="display: none;">
  <!-- Dynamic content goes here -->
</div>
<script>
  setTimeout(() => {
    document.getElementById('spinner').style.display = 'none';
    document.getElementById('content').style.display = 'block';
  }, 2000); // Simulates a 2-second data fetch
</script>
Enter fullscreen mode Exit fullscreen mode

Key Performance Concepts

  • Source Order: Arrange HTML source to prioritize critical content.
  • Critical Path: Minimize resources loaded initially to render the most important parts of the page quickly.
  • Latency: Reduce delays in data transfer to improve loading times.
  • Rendering: Understand how the browser processes and displays content.

Example: Critical Path Optimization

<link rel="stylesheet" href="critical.css">
<script src="critical.js" defer></script>
Enter fullscreen mode Exit fullscreen mode

Sustainability and Performance

  • Energy Efficiency: Optimized code reduces CPU usage and power consumption.
  • Demand Efficiency: Perform computations only when and where necessary.

2. Improving Page Rendering

Reducing Page Loading Times

  • Optimal Media Formats and Compression: Use WebP for images and compressed audio/video formats.
  • Remove Unnecessary Audio: Muted videos should not load audio tracks.
  • Preload Video: Use the preload attribute to manage video loading behavior.
  • Adaptive Streaming: Deliver video in chunks to optimize bandwidth.
  • Specify Dimensions: Prevent layout shifts by defining image and video dimensions.
  • Font Choices: Use smaller font files by including only necessary glyphs.

Example: Lazy Loading Images

<img src="placeholder.jpg" data-src="image.jpg" alt="Lazy Loaded Image" loading="lazy">
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const img = document.querySelector('img[data-src]');
    img.src = img.dataset.src;
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Improving "Time to Usable"

  • Minimal Initial Load: Display essential content first.
  • Background Data Loading: Load additional resources as needed.
  • Lazy Loading: Defer loading of non-critical resources.

Example: Initial Load Optimization

<div id="main-content">
  <!-- Essential content -->
</div>
<div id="additional-content" style="display: none;">
  <!-- Additional content -->
</div>
<script>
  window.addEventListener('load', () => {
    document.getElementById('additional-content').style.display = 'block';
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Enhancing Perceived Performance

  • Smooth Transitions: Use animations to transition between states.
  • Progress Indicators: Show spinners or progress bars.
  • Efficient Event Handling: Use keydown events for quicker response.

Example: Progress Bar

<div id="progress-bar" style="width: 0; height: 4px; background: green;"></div>
<script>
  function updateProgressBar() {
    const progressBar = document.getElementById('progress-bar');
    let width = 0;
    const interval = setInterval(() => {
      width += 10;
      progressBar.style.width = width + '%';
      if (width >= 100) clearInterval(interval);
    }, 100);
  }
  updateProgressBar();
</script>
Enter fullscreen mode Exit fullscreen mode

3. Measuring Performance

Key Metrics

  • First Contentful Paint (FCP): Time to render the first bit of content.
  • Speed Index: Average time for content to become visible.
  • Total Blocking Time (TBT): Time spent blocked by scripts.
  • Bounce Rate: Percentage of visitors who leave after viewing one page.
  • Unique Users/Page Views: Metrics from analytics tools.

Performance Measurement Tools

  • Google Lighthouse: Audits web pages for performance.
  • Pagespeed Insights: Provides performance scores and suggestions.
  • WebPageTest: Detailed performance analysis.
  • Browser DevTools: Built-in tools for network and performance monitoring.

Example: Using Google Lighthouse

  1. Open Chrome DevTools.
  2. Navigate to the "Lighthouse" tab.
  3. Click "Generate report" to analyze the current page.

Performance Web APIs

  • Performance Timeline API: Analyze various performance metrics.
  • Navigation Timing API: Measure load times.
  • User Timing API: Custom performance marks and measures.
  • Resource Timing API: Detailed timing data for resource requests.

4. CSS and Performance

Techniques for Improving CSS Performance

  • Conditional Loading: Use media queries to load CSS only when needed.
  • GPU Animations: Use properties like transform and opacity for smoother animations.
  • Minimize Repaints: Optimize CSS to reduce layout shifts.
  • Use will-change and contain: Indicate elements likely to change to the browser for optimization.

Example: GPU Animation

<style>
  .box {
    transition: transform 0.5s;
  }
  .box:hover {
    transform: translateX(100px);
  }
</style>
<div class="box">Hover over me!</div>
Enter fullscreen mode Exit fullscreen mode

5. JavaScript and Performance

Techniques for Improving JavaScript Performance

  • Reduce JavaScript Usage: Limit the amount of JavaScript on your pages.
  • Conditional Loading: Load scripts only when needed using async and defer.
  • Remove Unused Code: Eliminate dead code.
  • Code Splitting: Break down scripts into smaller parts for better loading.

Example: Deferred JavaScript

<script src="script.js" defer></script>
Enter fullscreen mode Exit fullscreen mode

JavaScript Optimization

  • Compression: Minify and compress JavaScript files.
  • Efficient Algorithms: Use optimized algorithms for data processing.
  • Event Delegation: Handle events efficiently to minimize performance impact.

Example: Event Delegation

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<script>
  document.getElementById('list').addEventListener('click', (event) => {
    if (event.target.tagName === 'LI') {
      alert('Item clicked: ' + event.target.textContent);
    }
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Improving JavaScript performance is crucial for creating fast, efficient, and user-friendly web applications. By understanding and implementing these techniques, you can ensure your websites load quickly and provide a smooth user experience.

Top comments (0)