MyTech Blog

Optimizing JavaScript Performance

JavaScript powers modern web applications, but unchecked code can quickly become a bottleneck. This guide covers practical techniques to keep your scripts fast and responsive.

1. Profile Before You Optimize

Use the built‑in browser dev tools to locate hot spots. In Chrome, open the Performance tab, record a session, and look for long‑running functions.

function heavyCalculation(arr) {
  return arr.reduce((sum, n) => sum + Math.pow(n, 3), 0);
}

2. Reduce Layout Thrashing

Reading layout properties (like offsetHeight) forces the browser to recalculate styles. Batch reads and writes.

// Bad
for (let i = 0; i < items.length; i++) {
  const h = items[i].offsetHeight;
  items[i].style.height = h + 20 + 'px';
}

// Good
let heights = [];
for (let el of items) heights.push(el.offsetHeight);
items.forEach((el,i) => el.style.height = heights[i] + 20 + 'px');

3. Leverage Asynchronous Loading

Defer non‑critical scripts with async or defer. Inline critical code and load the rest after the page is interactive.

<script src="large-lib.js" defer></script>

4. Use Web Workers for Heavy Tasks

Offload CPU‑intensive work to a background thread.

// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = e => console.log('Result:', e.data);

5. Minify and Tree‑Shake

During your build, remove dead code and compress the output. Tools like esbuild, terser, or webpack's production mode do this automatically.

6. Avoid Unnecessary Re‑renders in Frameworks

When using React, Vue, or similar, memoize expensive calculations and use proper keys.

const MemoizedComponent = React.memo(({data}) => {
  // renders only when data changes
});

7. Benchmark Real‑World Scenarios

Run performance tests on actual user devices. Tools like web-vitals provide metrics such as LCP, FID, and CLS.

By applying these strategies, you’ll deliver snappier experiences and keep your users engaged.