4

I'm including a Custom script in GTM that makes a call to an external resource. The script looks like this

<script type="text/javascript" id="some-key" data-key="xxxxxxxxxxxxxxxxxx" src="link-to-external-resource"></script>

I've set its triggering to All pages which currently triggers fine But the problem is, the script renders without the data-key attribute in the DOM. It's rendering in the DOM looks like this

<script type="text/javascript" id="some-key" src="link-to-external-resource"></script>

Am I missing something? Is there a way to include data-* attributes in Google Tag Manager?

anasey
  • 169
  • 12

1 Answers1

5

I can confirm that for unknown reasons GTM strips the data attributes from appended script elements. Other elements like img seems to keep data attributes. I've tested some workaround that preserves the data attributes but it's necessary to test if the appended script behaves properly when added in this way:

<script>
  var script = document.createElement('script');
  script.id = 'Gdf234ds'
  script.dataset.key = 'xxxxxxxxxxxxxxxxxx'
  script.src = "https://link-to-external-resource.js"

  // use another target than head if necessary
  document.getElementsByTagName('head')[0].appendChild(script) 
</script>
Дмитро Булах
  • 3,697
  • 1
  • 14
  • 23
  • Thank you, this appended the `data-key` as expected but doesn't trigger the link in the src attribute. It only gets to trigger the src attribute when a click is performed on the page but then because it reloads the script doesn't really get triggered. – anasey Feb 14 '20 at 10:11
  • could you please elaborate on how exactly your Custom HTML tag is triggered and what is supposed behaviour and functionality of the supposed script? It seems that the proper way to do this is to fire Custom HTML tag on page load event and I can't see how this is related to click events – Дмитро Булах Feb 14 '20 at 10:15
  • The script is usually appended just before the closing body tag and what it does is, it makes a request to the external URL to gather some specific data about the page that's currently running. As long as the page is still being viewed, the script continues to run and gather the data about that page – anasey Feb 14 '20 at 10:24
  • What's currently happening is, on page load, the custom tag (the sample above) gets created and appended to the DOM, but it doesn't trigger the script that has just been appended to the DOM – anasey Feb 14 '20 at 10:28