1] As @imvian2 and @Dragonsnap have mentioned above, you can also wrap the statement as such:
if (runCode) {
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','myNewName','GTM-XXXX');
}
2] Another possible way to do this, is to put the gtag code in it's own js file. Then you can load it with javascript.
WARNING: It is highly likely that google/gtag expects it's code to be placed directly in-page and not loaded in such a manner, so that it can detect all page load events. You will need to be aware of this and test, test, test.
RECOMMENDATION: I would do this with backend-code, NOT with js.
function addScript(scripts) {
// IE9
if (!Array.isArray(scripts)) scripts = [scripts];
for(var i=0, n=scripts.length; i < n; i++) {
var scriptElem = document.createElement('script');
scriptElem.async = false; // load scripts in order
scriptElem.src = scripts[i];
// IE9
var headElem = document.head || document.getElementsByTagName('head')[0];
headElem.appendChild(scriptElem);
}
}
var loadGtag = true;
if (loadGtag) {
addScript('/path/to/my/gtag-script.js');
}