Labs ICT
🎓 SIWES/IT Login

Performance Tips

2 min read | JavaScript Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

Minimize DOM Manipulations

Every time you touch the DOM, the browser may need to recalculate layout and repaint. Batch your DOM operations together to reduce reflows.

// Bad — triggers reflow on each iteration
for (let i = 0; i < 1000; i++) {
  document.querySelector("#list").innerHTML += `<li>Item ${i}</li>`;
}

// Good — one reflow
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const li = document.createElement("li");
  li.textContent = `Item ${i}`;
  fragment.appendChild(li);
}
document.querySelector("#list").appendChild(fragment);

Use Efficient Selectors

getElementById and querySelector are fast. Avoid getElementsByClassName in loops if you're modifying the collection — it returns a live HTMLCollection that updates as the DOM changes.

// Fast
const el = document.getElementById("myId");

// Also good
const el = document.querySelector("#myId");

// Avoid in performance-critical loops
const items = document.getElementsByClassName("item");

Debounce and Throttle

Don't run expensive functions on every event. Debounce waits until events stop firing; throttle limits execution to once per interval.

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Only search after user stops typing for 300ms
input.addEventListener("input", debounce((e) => {
  search(e.target.value);
}, 300));

Lazy Loading

Don't load everything upfront. Load images, components, or data only when they're needed — like when they scroll into view.

// Lazy load images
const images = document.querySelectorAll("img[data-src]");

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      img.removeAttribute("data-src");
      observer.unobserve(img);
    }
  });
});

images.forEach(img => observer.observe(img));

Summary

Performance is about reducing work: minimize DOM access, debounce expensive operations, and load data lazily. Small optimizations add up to a much faster experience.