With a positive mindset and your best effort, success is not just a possibility; it becomes a certainty. Google

How to lazyload Javascript using LocalStorage

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.

/**
 * Lazyload by Fineshop Design
 *
 * License: MIT
 */
window.lazy = new Promise((resolve) => {
  const localKey = "IS_LAZIED";
  const localValue = String(true);
  const windowEvents = [
    "keydown",
    "mouseover",
    "touchmove",
    "touchstart",
    "scroll",
    "click"
  ];
  function getLazied() {
    try {
      return localStorage.getItem(localKey) === localValue;
    } catch (_) {
      return true;
    }
  }
  function setLazied(lazied = true) {
    try {
      if (lazied) {
        localStorage.setItem(localKey, localValue);
      } else {
        localStorage.removeItem(localKey);
      }
    } catch (_) {
      // do nothing
    }
  }
  function execute(data) {
    setLazied(true);
    resolve({ type: data.type.toLowerCase() });
    for (const type of windowEvents) {
      window.removeEventListener(type, execute);
    }
  }
  if (getLazied()) {
    resolve({ type: "local" });
  } else {
    if (
      document.documentElement.scrollTop !== 0 ||
      (document.body && document.body.scrollTop !== 0)
    ) {
      execute({ type: "scroll" });
    }

    for (const type of windowEvents) {
      window.addEventListener(type, execute);
    }
  }
});

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.

lazy.then((e) => {
  // Load your JS dynamically
  // Make HTTP requests
  console.log(e.type) // Probably: scroll, local, click, etc.
});

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.then(() => { 
  return loadJS("./my-example-script.js", (script) => {
    // Add async attribute before loading
    script.async = true;
  });
}).then(() => {
  // 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.then(() => {
  const adsenseScriptSource = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX";
  return loadJS(adsenseScriptSource, (script) => {
    script.async = true;
    script.crossOrigin = "anonymous";
  });
}).then(() => {
  // Adsense script loaded
  // ...
});

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.

Creative Director | Designing Impactful Visual Stories | Transforming Ideas into Engaging Experiences

Post a Comment