ArticleZip > Using Google Analytics Asynchronous Code From External Js File

Using Google Analytics Asynchronous Code From External Js File

Have you ever wondered how to incorporate Google Analytics asynchronous code into your website from an external JavaScript file? If so, you're in the right place! This technique can streamline your code and help ensure that your tracking scripts load efficiently. In this article, we will guide you through the process step by step.

First off, what exactly is Google Analytics asynchronous code? This type of code allows your website to track user interactions without slowing down the loading speed of your site. It's a powerful tool for gathering valuable data about your visitors and their behavior on your website.

To begin, create a new JavaScript file where you will place the Google Analytics asynchronous code. You can name this file whatever you like, but for clarity, we recommend using a name related to Google Analytics, such as "google-analytics.js". Once you've created the file, open it in your favorite text editor.

Next, you will need to obtain your Google Analytics tracking ID. This can be found in your Google Analytics account under the Admin settings. Copy the tracking ID as you will need it to configure the asynchronous code in your JavaScript file.

In your new JavaScript file, you can create a function to load the Google Analytics script asynchronously. Here's an example function you can use:

Javascript

function loadGoogleAnalytics() {
  if (!window.ga) {
    window.ga = function () {
      (ga.q = ga.q || []).push(arguments);
    };
    ga.l = +new Date();
    ga('create', 'YOUR_TRACKING_ID', 'auto');
    ga('send', 'pageview');
    var script = document.createElement('script');
    script.async = true;
    script.src = 'https://www.google-analytics.com/analytics.js';
    document.body.appendChild(script);
  }
}

In the function above, be sure to replace 'YOUR_TRACKING_ID' with the tracking ID you copied from your Google Analytics account. This function checks if the Google Analytics script has already been loaded and if not, it creates a new GA function and loads the script asynchronously.

Lastly, you will need to call the `loadGoogleAnalytics()` function to initiate the loading of the Google Analytics script. You can do this by adding a simple line of code in your HTML file just before the closing `` tag:

Html

loadGoogleAnalytics();

Remember to replace "path/to/your/google-analytics.js" with the correct path to your JavaScript file.

And that's it! You've successfully set up Google Analytics asynchronous code from an external JavaScript file. This method can help optimize the performance of your website and ensure accurate tracking of user data. Happy tracking!

×