The site is under maintenance.

How to lazyload Javascript using LocalStorage

Learn efficient JavaScript lazy loading with LocalStorage for improved website performance.

Website performance is a critical factor in providing a smooth and enjoyable user experience. One common technique to enhance performance is lazy loading JavaScript. Lazy loading allows you to load JavaScript files only when they are needed, reducing initial page load times and conserving bandwidth. In this tutorial, we'll explore an interesting twist on lazy loading by leveraging the power of LocalStorage, a web storage technology available in modern browsers. By the end of this guide, you'll have a solid understanding of how to implement lazy loading with LocalStorage and optimize your website's performance.

Lazyload JS

I have written a JavaScript Library which can be used to lazyload resources. To use it, paste the following JavaScript code in the head section of your webpage.

/*! Lazy Function by Fineshop Design | uses HTML5 localStorage */
(function(e){var t=[];function n(e){"function"==typeof e&&(n.lazied||t.executed?e.call(window,{type:"LOCAL_STORAGE"}):t.push(e))}function o(){0==document.documentElement.scrollTop&&0==document.body.scrollTop||(t.execute({type:"SCROLL"}),window.removeEventListener("scroll",o))}function c(){t.execute({type:"CLICK"}),document.body.removeEventListener("click",c)}function d(){n.lazied||t.executed||(document.body.addEventListener("click",c),window.addEventListener("scroll",o),o()),document.removeEventListener("DOMContentLoaded",d)}t.executed=!1,n.lazied=localStorage.getItem(e.key)===e.value,t.execute=function(){if(!1===this.executed){this.executed=!0,n.lazied=!0,localStorage.getItem(e.key)!==e.value&&localStorage.setItem(e.key,e.value);for(let e=0;e<this.length;e++)"function"==typeof this[e]&&this[e].apply(window,arguments),this.splice(e,1),e--}},"complete"===document.readyState||"loading"!==document.readyState||null!==document.body?d():document.addEventListener("DOMContentLoaded",d),this[e.name]=n}).call(typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof this !== 'undefined' ? this : {}, { name: "Lazy", key: "LOCAL_LAZY", value: "true" });

Usage

You can call Lazy function with a callback function as an argument, the callback function will be called when user interacts with the page and so on.

function lazyCallback (arg) {
  // Load your JS dynamically
  // Make HTTP requests
  console.log(arg.type) // Probably: SCROLL, LOCAL_STORAGE, CLICK
}
Lazy(lazyCallback);

Examples

Here I have written a Javascript function loadJS to load Javascript from external sources dynamically.

/**
 * Function to load Javascript file
 * 
 * @author Deo Kumar <deo@fineshopdesign.com>
 * 
 * @param {string} source - Source of the script
 * @param {((script: HTMLScriptElement) => void) | null} [beforeLoad] - Function for modifying script element before loading
 * 
 * @returns {Promise<HTMLScriptElement>} - Returns a Promise which resolves with HTMLScriptElement instance
 */
function loadJS(source, beforeLoad) {
  return new Promise(function(resolve, reject) {
    const script = document.createElement("script");
    
    // Enable async and defer by default
    Object.assign(script, { async: true, defer: true });
    
    if (typeof beforeLoad === "function") {
      beforeLoad(script);
    }
    
    function cleanUp() {
      script.onload = null;
      script.onerror = null;
    }

    script.src = source;
    script.onload = function (e) {
      cleanUp();
      resolve(e.target);
    };
    script.onerror = function (e) {
      cleanUp();
      reject(new URIError("The script " + e.target.src + " didn't load correctly."));
    };

    const firstScript = document.getElementsByTagName("script")[0];

    if (firstScript && firstScript.parentNode) {
      firstScript.parentNode.insertBefore(script, firstScript);
    } else {
      document.head.appendChild(script);
    }
  });
};

We can use it in our Lazy function as shown belown:

Lazy(async () => {
  // Await promise to ensure resource is loaded
  await loadJS("./my-example-script.js", (script) => {
    // Add async attribute before loading
    script.async = true;
  });
  
  // JS is lazyloaded, perform actions here
  // myExampleLib.myMethod();
});

Lazyload Adsense Script

You can lazyload AdSense Script using this library, an example is shown below:

Lazy(() => {
  const adsenseScriptSource = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX";
  loadJS(adsenseScriptSource, (script) => {
    script.async = true;
    script.crossOrigin = "anonymous";
  });
});

Conclusion

Lazy loading JavaScript using LocalStorage is a powerful strategy to enhance your website's performance and user experience. By deferring the loading of non-essential scripts until they are needed, you can improve initial page load times and reduce bandwidth usage. This tutorial will guide you through the process of implementing this technique effectively, helping you create faster, more efficient websites for your users.

About the Author

Hey! I'm Deo Kumar, a passionate web developer skilled in JavaScript, Node.js, Cloudflare Workers, KV stores, and Next.js. With a focus on dynamic web applications, I excel in JavaScript and Node.js, ensuring robust websites. As a front-end expe…

4 comments

  1. How to implememtation ?
    1. I have updated the post describing how you can implement it with few examples.
  2. hello sir,
    Where you have written "Load your JS dynamically" and "Make HTTP requests" in these two places, please tell me how to put them.
    1. Hey, I have updated the example code which shows how you can lazyload JavaScript from external sources. In the same way, you can make HTTP requests using XMLHttpRequest Constructor or Fetch API.
      Thank you!
To avoid SPAM, all comments will be moderated before being displayed.
Don't share any personal or sensitive information.
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.