The marketing department wants to separate the Google Tag Manager per country. For an normal website, not SPA, we can easily do this based on the URL. Would the client switch to another URL, then the page would be refreshed, country code added in the URL and the correct GTM can be loaded.
Now for a SPA (in Angular,Typescript) this is a little bit harder. Currently we don't have a language/country parameter in this application, but it can be changed anyways throughout the web application. Of course the page would not be refreshed.
I am trying to find a way to dynamically load and unload GTM script.
I can successfully load and unload an <script>
element in the <head>
but the tag manager adds more elements.
public loadScriptSimple(country : string) {
//first remove existing node
var existing = document.getElementById("tagmanager");
if (existing && existing.parentNode) {
existing.parentNode.removeChild(existing);
}
//
console.log('adding node to head...');
let node = document.createElement('script');
if (country === "NL") {
node.textContent =
"(function (w, d, s, l, i) {w[l] = w[l] ....(window, document, 'script', 'dataLayer', 'GTM-XXX');";
} else {//todo for later loading others
node.textContent =
"(function (w, d, s, l, i) {w[l] = w[l] ....(window, document, 'script', 'dataLayer', 'GTM-YYY');";
}
node.type = 'text/javascript';
node.async = true;
node.charset = 'utf-8';
node.setAttribute("id", "tagmanager");
document.getElementsByTagName('head')[0].appendChild(node);
console.log('loaded script');
}
Source: https://stackoverflow.com/a/38473334/2901207
So it would be possible to load it on the first request (e.g. the first time the country is decided based on IP) but after changing the country, two tags would be loaded.
Is there any simple way to remove the existing elements and then create the new ones like above?