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 belown:
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.