I am trying to add Google Analytics to my site dynamically only after the use clicks "I Accept Cookies".
The script that I have so far is
<script>
function addScript() {
var addGoogleAnalytics = document.createElement("script");
addGoogleAnalytics.setAttribute("src","https://www.googletagmanager.com/gtag/js?id=G-MYIDHERE");
addGoogleAnalytics.async = "true";
document.head.appendChild(addGoogleAnalytics);
var addDataLayer = document.createElement("script");
var dataLayerData = document.createTextNode("window.dataLayer = window.dataLayer || []; \n function gtag(){dataLayer.push(arguments);} \n gtag('js', new Date()); \n gtag('config', 'G-MYIDHERE');");
addDataLayer.appendChild(dataLayerData);
document.head.appendChild(addDataLayer);
}
</script>
This is triggered using a simple
<a href="#" onclick="addScript();">Click Here</a>
This seems to work fine, but my questions are:
Is there a better way to do this? I am no expert at javascript, so I am a little surprised it works and want to make sure there are no major code/security risks before deploying.
More importantly.. How do I store the "I accept" in a cookie or localStorage so that they do not have to click I accept each time, and if that is set it loads the script automatically without the onclick function?