Forum Discussion

Join our Telegram Group 👉 Netwem
| ♻️ The site is under maintenance.
All best selected devices reviewed made available here


We offer various Tech products and special products for you, support the work of the nation's children by buying the products we sell

Welcome to NetHouse Digi Shop...

  • Download theme blogger mirip xmlthemes.com

    Tech Deals at its best

    stay tune to for more lagi Discount 50%
    $153.000
  • Download theme blogger mirip xmlthemes.com

    Tech Deals at its best

    stay tune to for more lagi Discount 50%
    $153.000
  • Download theme blogger mirip xmlthemes.com

    Tech Deals at its best

    stay tune to for more lagi Discount 50%
    $153.000
  • Download theme blogger mirip xmlthemes.com

    Tech Deals at its best

    stay tune to for more lagi Discount 50%
    $153.000
  • Download theme blogger mirip xmlthemes.com

    Tech Deals at its best

    stay tune to for more lagi Discount 50%
    $153.000
  • 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.

    Lazy 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(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(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 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
    * @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;
    };

    We can use it in our Lazy function as shown 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

    You can lazyload AdSense Script using this library, an example is shown 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";
    });
    });

    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.

    Check this Out:

    Thanks for reading: How to lazyload Javascript using LocalStorage, Stay tune for more..

    DMCA: Netwem.com complies with 17 U.S.C. * 512 and the Digital Millennium Copyright Act (DMCA). It is our policy to respond to any infringement notices and take appropriate action. If your copyrighted material has been posted on the site and you want this material removed, Contact us. 👉 Here


    📍Note📍

    This Is A Promotional Website Only, All Files Placed Here Are For Introducing Purposes Only. All Files Found On This Site Have Been Collected From Various Sources Across The Web And Are Believed To Be In The “Public Domain”. If Have Any Other Issues Then Feel Free To Contact Us.

    About the Author

    👨‍💻 Software Engineer | Technical Writer 📝

    Post a Comment

    🌟 Enter Image URL or Code snippets, or Quote, then click the button you want to parse. Copy the parse result and paste it into the comment section. 🌟


    image quote pre code
    Cookie Consent
    We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
    Oops!
    It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
    AdBlock Detected!
    We have detected that you are using adblocking plugin in your browser.
    The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
    Site is Blocked
    Sorry! This site is not available in your country.