Open PortfolioOpen Portfolio.
โ† Back to Blog

How to Lazy Load Third-Party Scripts

March 19, 2026at 2:01 PM UTCBy Pocket Portfolio Teamperformance
How to Lazy Load Third-Party Scripts
#lazy loading#third-party scripts#performance

Problem

Web applications often rely on third-party scripts for functionalities such as analytics, social media widgets, or ads. While these scripts add value, they can significantly slow down page load times. Loading all scripts upfront increases Time to Interactive (TTI) and can degrade user experience, especially on slower networks. The solution is to lazy load these scripts, ensuring they are only loaded when necessary.

Solution with Code

Lazy loading involves deferring the loading of third-party scripts until they are needed, typically when they come into the user's viewport or based on user interactions. Here's a simple implementation using JavaScript:

function loadScript(src, callback) {
  const script = document.createElement('script');
  script.src = src;
  script.async = true;
  script.onload = callback;
  document.body.appendChild(script);
}

function lazyLoadScript(selector, scriptUrl) {
  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        loadScript(scriptUrl, () => {
          console.log(`Script loaded: ${scriptUrl}`);
        });
        observer.unobserve(entry.target);
      }
    });
  });

  const targetElement = document.querySelector(selector);
  if (targetElement) {
    observer.observe(targetElement);
  }
}

// Usage
lazyLoadScript('#target-element', 'https://example.com/third-party-script.js');

Explanation

  1. loadScript Function: A utility function that dynamically creates a script element, sets its source, and appends it to the document body. It includes an optional callback executed once the script loads.

  2. lazyLoadScript Function: Utilizes the IntersectionObserver API to observe a specified DOM element. When the element becomes visible in the viewport, it triggers the loadScript function to load the third-party script.

  3. IntersectionObserver: This modern API efficiently monitors elements as they enter or exit the viewport, making it ideal for lazy loading content. It optimally uses system resources compared to scroll events.

  4. Usage: You define the target element (#target-element) and the script URL you wish to lazy load. The script will only be loaded when the user scrolls the target element into view.

Key Concepts

  • Lazy Loading: Defers loading of non-critical resources at page load time. Instead, resources are loaded when they are needed.

  • IntersectionObserver API: Provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or the top-level document's viewport.

  • Performance Improvement: By reducing the initial load time, lazy loading enhances page performance and user experience, particularly beneficial for mobile users and those on slower connections.

Implementing lazy loading for third-party scripts is a strategic optimization that can significantly improve your web application's performance. By ensuring scripts load only when needed, you create a more responsive and faster user experience.

How to Lazy Load Third-Party Scripts | Open Portfolio Blog | Open Portfolio