Lazy Loading JavaScript Without Frameworks or Libraries

Lazy loading is a performance optimization technique that delays the loading of JavaScript files until they are needed. This can significantly improve the initial load time of your web pages, especially when dealing with large scripts or heavy applications.

Another use for lazy loading is to configure your website with only the required plugins / components at runtime, allowing dynamic content and plugin functionality.

This blog post describes how you can implement lazy loading in vanilla javascript without any other library or framework dependency.

The steps involved are outlined below :

  • Create a basic html webpage that contains a button and a custom html tag ( a sample web component that is not defined yet )
  • Add a click listener on the button that will load a script and execute it ( this will define the web component and will render it )

Initial setup

First we will create a basic index.html file that contains a button and also the markup for a sample web component current-date . We will also include a initial js script load-plugin that will attach event listener on the button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Plugin</title>
<script src="./load-plugin.js" ></script>
</head>
<body>
<h1>JS Plugin</h1>
<button id="load-plugin-button">Load Plugin</button>
<current-date></current-date> </body>
</html>

We are attaching a click event listener on the button, which will programmatically add a script tag to the document head. This will trigger the browser to fetch the script /plugin.js . This script can be hosted anywhere, for this example I have added the script in the same web server directory.

// Fetch Plugin
document.addEventListener("DOMContentLoaded", function (event) {
  /* 
      - Code to execute when only the HTML document is loaded.
      - This doesn't wait for stylesheets, 
        images, and subframes to finish loading. 
    */
  const loadPluginButton = document.getElementById("load-plugin-button");

  // add event listener to the button
  loadPluginButton.addEventListener("click", () => {
    let plugin_script = document.createElement('script');
    plugin_script.setAttribute('src','/plugin.js');
    document.head.appendChild(plugin_script);
  });
});

The plugin.js script contains code to define a web component called current-date . This is a simple web component that renders the current date.

class CurrentDate extends HTMLElement {
    // The browser calls this method when the element is
    // added to the DOM.
    connectedCallback() {
        // Create a Date object representing the current date.
        const now = new Date();
        
        // Format the date to a human-friendly string, and set the
        // formatted date as the text content of this element.
        this.textContent = now.toLocaleDateString();
    }
}

// Register the CurrentDate component using the tag name .
customElements.define('current-date', CurrentDate);

That’s it. Below you can see the demo on how it works . You can find the source code here.

Sign up for our newsletter

Stay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.