Skip to content

Instantly share code, notes, and snippets.

@peazz
Last active August 11, 2021 11:12
Show Gist options
  • Save peazz/fba94a2c2e19b949831d647609448cbd to your computer and use it in GitHub Desktop.
Save peazz/fba94a2c2e19b949831d647609448cbd to your computer and use it in GitHub Desktop.
Delay AdSense & Google Analytics Until After DOM Loaded
/**
* Delay Adnsense & Google Analytics Until After DOM Loaded
* by: Andy Cresswell (@andy_ppsu)
* https://twitter.com/andy_ppsu
* #JavaScript #JS #AdSense #Analytics #CWV #CoreWebVitals #PageExperience
*
* This script, written in pure javascript, will help your improve your Core Web Vitals by delaying Javascript
* until after the DOM has loaded. Use with caution as some site may see an earnings
* drop. This is because adverts above the fold will be slight delayed.
*
* This method should be considered due to the HUGE UX benefits for your website users. Your entire website will
* feel more responsive by delaying the stuff impacting rendering times the most
*
* INSTRUCTIONS:
*
* 1. Remove all existing universial analytics and adsense script tags
* 2. replace the ca-pub-1234567890 with your own adsense account id
* 3. Replace the Universial Analyutics id with your own
* 4. Place the script in your footer and exclude it from any lazy loading processes
* 5. Enjoy Improved Core Web Vitals
**/
<script type="text/javascript" data-no-optimize="1">
function downloadJSOnDOMloaded() {
// include adsense
var ads = document.createElement("script");
// change the client variable to match your client id
ads.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890";
document.body.appendChild(ads);
// include adsense
var adsense = document.createElement("script");
// change the UA code to match your own
adsense.src = "https://www.googletagmanager.com/gtag/js?id=UA-123456789-1";
document.body.appendChild(adsense);
}
if (window.addEventListener) window.addEventListener("load", downloadJSOnDOMloaded, false);
else if (window.attachEvent) window.attachEvent("onload", downloadJSOnDOMloaded);
else window.onload = downloadJSOnDOMloaded;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment