๐ JavaScript Performance Tips
Writing efficient JavaScript not only improves user experience but also boosts SEO and reduces CPU usage. Here's a set of practical tips to write faster, leaner code.
๐ฏ 1. Minimize DOM Access
Accessing and manipulating the DOM is relatively slow. Cache DOM lookups and avoid excessive changes.
// โ Bad
document.getElementById("user").style.display = "none";
document.getElementById("user").style.color = "red";
// โ
Better
const userEl = document.getElementById("user");
userEl.style.display = "none";
userEl.style.color = "red";
๐ 2. Debounce & Throttle Events
Prevent rapid-fire event handlers (like scroll
or resize
) from bogging down performance.
// Debounce Example
function debounce(func, delay) {
let timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(func, delay);
};
}
window.addEventListener("resize", debounce(() => {
console.log("Window resized!");
}, 300));
๐งฎ 3. Use Local Variables
Local variables are faster to access than globals or object properties.
// โ Slower
for (let i = 0; i < arr.length; i++) {}
// โ
Faster
const len = arr.length;
for (let i = 0; i < len; i++) {}
๐งน 4. Remove Unused Code & Variables
Clean, minimal code runs faster and is easier to maintain. Dead code also bloats bundle size.
๐ฆ 5. Minify & Bundle
Use tools like Vite
, Webpack
, or esbuild
to minify and bundle your JS files for production.
๐ 6. Load Scripts Efficiently
- Use
defer
to delay script execution until DOM is ready. - Place scripts at the end of
<body>
if not usingdefer
. - Use
async
for third-party, non-blocking scripts.
<script src="main.js" defer></script>
๐ง 7. Avoid Memory Leaks
Always clean up timers, intervals, and event listeners to prevent memory bloat.
const interval = setInterval(() => {
// Do something
}, 1000);
// Clear it when no longer needed
clearInterval(interval);
๐ 8. Profile and Measure
- Use Chrome DevTools โ Performance Tab
- Use
console.time()
andconsole.timeEnd()
- Look for slow scripts, reflows, and repaints
console.time("loop");
for (let i = 0; i < 10000; i++) {
// simulate task
}
console.timeEnd("loop");
โ Summary Checklist
- Minimize DOM access
- Debounce/throttle expensive events
- Cache values in loops
- Clean unused code
- Use efficient loading strategies
- Profile and fix performance bottlenecks
Apply these tips to every project for a smoother, faster JavaScript experience!