JavaScript

Google Analytics Tag Integration via External JS File: Complete Guide

Understanding your website’s traffic is a critical factor for its success. Google Analytics is a powerful tool that makes this possible.
In this article, we’ll explain in detail how to integrate Google Analytics into your website using an external JavaScript file.

What is Google Analytics?

Google Analytics is a free tool for analyzing website traffic. It provides various data such as the number of visitors, the most popular pages, and the routes visitors took to reach your website. By utilizing this information, you can identify areas for improvement and plan marketing strategies effectively.

Why Use an External JS File?

The biggest advantage of using an external JS file is ease of management. You can apply changes across the entire site by editing a single file. It can also help improve page load speed.

Step 1: Create an External JS File

First, create an external JavaScript file named `head.js`. You will add the Google Analytics tags to this file later.

Step 2: Write the Google Analytics Tag

Next, add the following Google Analytics tags into the `head.js` file you created. Replace `XXXXXXXXXX` with your GA4 measurement ID and `111111111` with your UA tag measurement ID.

document.write('<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>');

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

gtag('config', 'G-XXXXXXXXXX');
gtag('config', 'UA-111111111-1');

 
This code loads the Google Analytics library asynchronously and sends pageview data to Google Analytics.

Step 3: Embed the Tag into Your Web Page

Next, add the following line into the `` section of each web page to load the `head.js` file you created earlier.

<script src="path/head.js"></script>

 
That’s it! Now publish your website and wait for the data to be sent to Google Analytics.

Demo Page: Tracking Access with Google Analytics Tag via External JS File

To see how it actually works, check out the demo page below:

Demo Page: Tracking Access with Google Analytics Tag via External JS File

Conclusion

In this article, we explained how to integrate the Google Analytics tag into your website using an external JavaScript file. By following this method, you can efficiently collect and analyze traffic data for your website.

 
*Use at your own risk.
Please do not reuse the Google Analytics tag in the head section of the demo page.*