In JavaScript, as in many other programming languages, variables have a scope – global or local / block.
Functions also have a scope, if they were defined inside other functions.
Here is an example:
1 2 3 4 5 6 7 8 9 |
function loadAnalytics(){ var imported = document.createElement('script'); imported.src='https://www.googletagmanager.com/gtag/js?id=XXXXX'; document.head.appendChild(imported); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'XXXXX'); } |
Trying to use the “gtag” function outside the “loadAnalytics” function will not work. The function is limited in scope. In order to use it globally, the simplest solution would be to create a global variable and then assign this function to the variable.
Updated code:
1 2 3 4 5 6 7 8 9 10 |
var gtag=function(){}; function loadAnalytics(){ var imported = document.createElement('script'); imported.src='https://www.googletagmanager.com/gtag/js?id=XXXXX'; document.head.appendChild(imported); window.dataLayer = window.dataLayer || []; gtag=function(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'XXXXX'); } |
Simple adjustment and now “gtag” is widely accessible!