3

I have an HTML code that has only one line of code:

<script async src="https://www.googletagmanager.com/gtag/js?id=ID"></script>

But I do not want to use HTML at all. Since I am performing all my functions inside my javascript, can I add the above code inside my JavaScript? If so, how?

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'ID');
Vika
  • 419
  • 1
  • 13
  • 7
    If you don't want to use HTML at all, how will you execute the JS file in your users browser? – Jeremy Thille Jan 19 '22 at 15:18
  • 4
    HTML is a fundamental part of the web. What purpose does this page server? – evolutionxbox Jan 19 '22 at 15:18
  • Simply writing `` on every page means that you don't need to reuse as much code. For example, if you wanted to change the ID (and you weren't using any fancy server-side code), you would have to go through every page to do so. – TheKodeToad Jan 19 '22 at 15:24
  • Yes HTML is required to load a webpage. I understand that and although I am using HTML with javascript, I just wanted to know if there is a way to add an html code to load a javascript inside another javascript. – Vika Jan 20 '22 at 08:28

1 Answers1

0

To answer my own rhetorical question, there is a way to append url inside my javascript by this way:

function appendScript(){
    var script = document.createElement("script");
    script.src = "https://www.googletagmanager.com/gtag/js?id=ID"; 
    document.head.appendChild(script);
}

appendScript();
Vika
  • 419
  • 1
  • 13