Here’s an example of a lazy loading JavaScript snippet that can help you to load Google Analytics and Google AdSense tags asynchronously, which can improve website loading times:
This code creates two functions, lazyLoadScript
and lazyLoad
. The lazyLoadScript
function creates a new script element, sets its type and source URL, and adds it to the head of the HTML document. The lazyLoad
function calls lazyLoadScript
to load the Google Analytics and Google AdSense scripts.
Finally, the code uses an event listener to trigger the lazyLoad
function when the page has finished loading. The event listener is set up to work with different browser versions.
To use this code, simply copy and paste it into the head section of your HTML document, replacing the URLs with your own Google Analytics and Google AdSense script URLs. This will ensure that these scripts are loaded asynchronously after the page has finished loading, improving the page’s loading times.
<script>
function lazyLoadScript(url) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.async = true;
document.getElementsByTagName("head")[0].appendChild(script);
}
function lazyLoad() {
// Lazy load Google Analytics
lazyLoadScript("https://www.google-analytics.com/analytics.js");
// Lazy load Google AdSense
lazyLoadScript("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js");
}
if (window.addEventListener) {
window.addEventListener("load", lazyLoad, false);
} else if (window.attachEvent) {
window.attachEvent("onload", lazyLoad);
} else {
window.onload = lazyLoad;
}
</script>
Sources and Resources, the above was written with the help of ChatGPT and ChatGPT referenced the following sources:
Content Creation: ChatGPT can generate high-quality, keyword-optimized content to improve search engine rankings. Understanding User…
To bypass expenses, hackers create "miner botnets," networks of infected computers that mine cryptocurrency without…
Conversion rate optimization will become the guiding argument for most digital development. And it will…
As a web optimization professional, it is essential to manage your customers' expectations and educate…
here's a step-by-step guide to setting up website metrics and KPIs to begin an optimization…
A/B testing, also known as split testing, is a powerful technique used by businesses and…