Learn business growth with Google Analytics 4 Forums Google Analytics 4 What is the process to incorporate the GA4 tag into a separate .js file?

  • What is the process to incorporate the GA4 tag into a separate .js file?

    Posted by Kelsey on 7 January 2023 at 5:38 pm

    Hey there, I’m having a bit of a doozy. You see, I’ve got this script in the element on my webpage to do the job of tracking analytics with GA4 code, and that’s smooth sailing. But where I’m hitting a wall is trying to figure out how to give the new gtag.js script a spin in an external file. Any bright ideas?

    For a wee bit of background, here’s the script I use in the element.

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=TRACKINGID"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'TRACKINGID');
    </script>
    
    Mia replied 12 months ago 2 Members · 1 Reply
  • 1 Reply
  • Mia

    Member
    11 April 2023 at 5:03 pm

    Sure, I can definitely help with that. In layman’s term, you want to move that existing ‘script’ tag code into an external .js file and then reference that file on your webpage. Here’s how you can do it:

    Firstly, you need to create a new .js file. You can use any text editor to do this, just make sure you save it with a .js extension.

    Secondly, you should copy all the JavaScript code — that is, everything between the ‘script’ tags on your webpage — into this new .js file.

    And finally, you should replace the old ‘script’ tag on your webpage with a new one. This new ‘script’ tag will link to your external .js file. The ‘src’ attribute in your ‘script’ tag should be set to the URL or path of your .js file.

    And that’s it! You’ve successfully moved your JavaScript code to an external file. Don’t forget to replace ‘TRACKINGID’ with your actual tracking ID both in the external file and the webpage. The advantage of using an external .js file is it helps to keep your HTML document clean and easy to understand, and it allows your JavaScript to be cached, which can improve page load speed.

Log in to reply.