(Make your JavaScript applications faster, smoother, and more efficient)
JavaScript runs in the browser. Poor performance can cause:
Optimizing your code ensures:
for (let i = 0; i < 1000; i++) {
const div = document.createElement("div");
document.body.appendChild(div);
}const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const div = document.createElement("div");
fragment.appendChild(div);
}
document.body.appendChild(fragment);Using DocumentFragment reduces layout recalculations and repainting.
function debounce(fn, delay) {
let timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
};
}
window.addEventListener("resize", debounce(() => {
console.log("Resized!");
}, 300));function throttle(fn, limit) {
let lastCall = 0;
return function () {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn();
}
};
}for (let i = 0; i < array.length; i++) {
if (array.length > 0) { /* redundant check */ }
}const len = array.length;
for (let i = 0; i < len; i++) {
// ...
}Also, avoid nested loops if possible or use map(), filter(), or reduce() effectively.
Set instead of arrays for unique values.Map instead of plain objects for key-value storage.Only load what’s needed.
button.addEventListener("click", async () => {
const { heavyFunction } = await import("./heavy.js");
heavyFunction();
});Split large JavaScript bundles into smaller chunks to reduce initial load.
Minification removes whitespace, comments, and shortens variable names.
Use tools like:
mode: 'production'Also enable Gzip or Brotli compression on your server.
element.removeEventListener("click", handler);
element = null;| Technique | Benefit |
|---|---|
DocumentFragment | Fewer DOM updates |
debounce() / throttle() | Smoother event handling |
Map / Set | Better performance on large data |
| Lazy loading | Faster initial page load |
| Minify & compress JS | Smaller download sizes |
Efficient JavaScript isn't just faster — it's smarter and scalable.
DocumentFragment.scroll or resize event.Set instead of an array to remove duplicates.import() function.