Join our Telegram group to get instant answers to all your questions, stay updated with the latest posts, and receive regular updates: Join Now!.

How to lazyload Javascript using LocalStorage

Master JavaScript lazy loading with LocalStorage for a performance boost on your website.

Improving website performance is crucial for delivering a seamless user experience. A widely adopted strategy for enhancing performance involves lazy loading JavaScript, which enables the loading of JavaScript files only when necessary. This not only reduces initial page load times but also conserves bandwidth.

How to lazyload Javascript using LocalStorage

In this tutorial, we'll delve into an innovative approach to lazy loading by harnessing the capabilities of LocalStorage, a modern web storage technology supported by browsers. By the end of this guide, you'll have a comprehensive grasp of implementing lazy loading with LocalStorage, empowering you to optimize your website's performance effectively.

I've crafted a JavaScript Library designed for seamless resource lazy loading. To integrate it into your webpage, simply copy and paste the following JavaScript code into the head section of your site.

/*! Lazy Function by It Is Unique Official | 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(this,{name:"Lazy",key:"LOCAL_LAZY",value:"true"});

Usage

Invoke the Lazy function by including a callback function as its parameter. This callback function gets triggered when users interact with the page or engage in other activities.

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(source: string, beforeLoad?: ((script: HTMLScriptElement) => void) | null, onload?: ((event: Event) => void) | null, onerror?: ((event: Event) => void) | null) => HTMLScriptElement to load Javascript from external sources dynamically.

/**
 * Function to load Javascript file
 * 
 * @author It Is Unique Official <itisuniqueofficial@gmail.com>
 * 
 * @param {string} source - Source of the script
 * @param {((script: HTMLScriptElement) => void) | null} [beforeLoad] - Function for modifying script element before loading
 * @param {((event: Event) => void) | null} [onload] - Callback function for onload event
 * @param {((event: Event) => void) | null} [onerror] - Callback function for onerror event
 * 
 * @returns {HTMLScriptElement} - Returns the created HTMLScriptElement instance
 */
function loadJS(source, beforeLoad, onload, onerror) {
  const script = document.createElement("script");
  
  if (typeof beforeLoad === "function") {
    beforeLoad(script);
  }
  
  script.src = source;

  if (typeof onload === "function") {
    script.onload = onload;
  }
  
  if (typeof onerror === "function") {
    script.onerror = onerror;
  }

  const firstScript = document.getElementsByTagName("script")[0];
  
  if (firstScript && firstScript.parentNode) {
    firstScript.parentNode.insertBefore(script, firstScript);
  } else {
    document.head.appendChild(script);
  }
  
  return script;
};

You can seamlessly integrate it into our Lazy function, as illustrated below:

Lazy(function () {
  loadJS("./my-example-script.js", function (script) {
    // Add async attribute before loading
    script.async = true;
  }, function () {
    // JS is lazyloaded, perform actions here
    // myExampleLib.myMethod();
  });
});

Lazyload Adsense Script

Utilize this library to implement lazy loading for AdSense scripts. An illustrative example is provided below:

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

Disclaimer:
Warning - All content and posts on this platform are the intellectual property of It Is Unique Official. Unauthorized copying, reproduction, or distribution of our content is strictly prohibited. Any attempt to replicate or use our material without explicit permission may result in legal action. Please respect our intellectual property rights and contact us for inquiries regarding the use of our content. Thank you for your understanding and cooperation.

Conclusion

Elevate your website's performance and user experience with the potent technique of lazy loading JavaScript through LocalStorage. By postponing the loading of non-essential scripts until their necessity arises, you can significantly enhance initial page load times and minimize bandwidth consumption. This tutorial serves as a comprehensive guide, walking you through the seamless implementation of this technique and empowering you to craft faster, more efficient websites for an enhanced user experience.

Versatile Professional | Blogger, Web Developer, & Trader | Bridging Content Creation, Tech Innovation, & Financial Markets

You may like these posts

Post a Comment

Enter Image URL / Code Snippets / Quotes / name tag, then click parse button accordingly that you have entered. then copy the parse result and paste it into the comment field.


Cookie Consent

We use cookies on our website to analyze traffic, enhance your browsing experience, and remember your preferences. By continuing to use our site, you consent to our use of cookies. You can manage your cookie preferences in your browser settings. For more information, please read our Privacy Policy.

Google Translate
Bookmark Post