Sobes.tech
Middle

What methods can we use to speed up resource loading on the frontend?

sobes.tech AI

Answer from AI

  • Minification and compression of CSS/JS/HTML files.
  • Lazy loading of images.
  • Image optimization (compression, use of modern formats like WebP).
  • Use of CDN (Content Delivery Network).
  • Browser caching for static resources.
  • Code splitting to reduce the initial size of JavaScript bundles.
  • Prioritizing the loading of critical resources (e.g., fonts or CSS for the first screen).
  • Use of HTTP/2 and HTTP/3.
  • Preloading and prefetching of resources.
  • Removing unused code (Tree Shaking).
// Example of lazy loading images with Intersection Observer
document.addEventListener("DOMContentLoaded", function() {
  const lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

  if ("IntersectionObserver" in window) {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.srcset = lazyImage.dataset.srcset;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Fallback for browsers without Intersection Observer
    console.log("Intersection Observer not supported");
  }
});
<!-- Using preload and prefetch attributes -->
<link rel="preload" href="/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="prefetch" href="/js/next-page.js" as="script">