Lazy loading Google Analytics script in Angular: A step-by-step guide

Currently I am working with Angular 8 and I am interested in lazily loading my Google Analytics script. I came across some documentation that mentioned globally loading scripts lazily using the script array in angular.json:

"scripts": [
  "src/global-script.js",
  { "input": "src/lazy-script.js", "lazy": true },
  { "input": "src/pre-rename-script.js", "bundleName": "renamed-script" },
],

You can find more information about this on this link.

However, it seems like this method is now deprecated and there are no clear references in the new docs.

Using GTM (Google Tag Manager) has been affecting the load time of my app, so I am looking for a way to activate GTM only after my Angular app has loaded initially.

Do any of you have an example or suggestion on how to achieve this?

Thank you.

Answer №1

To achieve this functionality, you can utilize a combination of promises and services. Essentially, you will need to create a service that dynamically injects script tags into the body and sets the path to the script. Once the path is set, resolve the promise so that the script's functionality can be utilized. For a comprehensive example, refer to Ben Nadel's blog.

export class DelayedScriptLoader {

private delayInMilliseconds: number;
private scriptPromise: Promise<void> | null;
private urls: string[];

// Constructor for the delayed script loader service.
constructor( urls: string[], delayInMilliseconds: number );
constructor( urls: string, delayInMilliseconds: number );
constructor( urls: any, delayInMilliseconds: number ) {
    // Code implementation here
}
// Public methods implementation here

// Private methods implementation here
}

}

// Import statements

interface AnalyticsScript {
    // Interface definition
}

export type UserIdentifier = string | number;

export interface UserTraits {
    [ key: string ]: any;
}

export type EventIdentifier = string;

export interface EventProperties {
    [ key: string ]: any;
}

@Injectable({
    providedIn: "root"
})
export class AnalyticsService {
    // Class implementation here
}

Below is an example component utilizing the service:

// Import statements

@Component({
    selector: "my-app",
    styleUrls: [ "./app.component.less" ],
    template:
    `
        <p>
            <a (click)="doThis()">Do This</a>
            &mdash;
            <a (click)="doThat()">Do That</a>
        </p>
    `
})
export class AppComponent {
    // Component implementation here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a module with routes is imported into another module with lazy-loading, the routing system becomes disrupted

Within our angular application running version 4.3.6, we have implemented lazy-loaded modules such as Fleet, Maintenance, and Car. Examining our primary app router structure: const routes: Routes = [ { path: '', redirectTo: 'fleet', ...

"Interacting with the ng-keypress event causes the page to smoothly scroll

As a newcomer to angularjs, I am trying to figure out why my component (which simulates a "checkbox" using fontawesome icons) causes the page to scroll down when the user presses the space key. Here is a snippet of my component : ugoFmk.component(' ...

Angular - Exploring the process of creating a secondary standalone build for a specific section of an application

I have created an Angular 4 (or 5) application with a specific structure as shown in the image below: https://i.sstatic.net/zK1BM.png Now, I need to develop a separate standalone angular application where only a selected group of Angular components from ...

Oops! Looks like there was an issue with parsing the module. It seems there is an unexpected character '@' in the file. Make sure you have the proper loader configured to handle this file type

Angular version: 14.2.7 I added a unique CSS library to my Angular project that is not publicly available. After adding it to app.module.ts: import { SapphireButtonModule } from '@sapphire-angular/core'; imports: [ SapphireButtonModule, ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

Encountering a bad request error while attempting to update a numeric value in MongoDB

I attempted to update a single element in mongodb, specifically a number value. Below is the request sent to the DB: const handleDelivered = (num) =>{ const total = service.quantity; const final = parseInt(total) + num; console.log(tota ...

The upload method in flowjs is not defined

I am a novice when it comes to flow.js and am currently using the ng-flow implementation. I have a specific task in mind, but I'm unsure if it's feasible or not, and if it is possible, how to achieve it. I've created a factory that captures ...

Mocking an injectable Angular2 service

My setup involves Angular 2 Karma-Jasmine with a service called AService. it("test", () => { let x:any = function1('value', aService); expect(x).toEqual("value1"); }); AService now includes a method called getA(), and function1 relie ...

Looking for a jQuery Gantt Chart that includes a Treeview, Zoom functionality, and editing capabilities?

I am in need of integrating a dynamic Gantt Chart tool into a room booking solution using jQuery. The Gantt chart should be highly interactive, allowing for drag-and-drop functionality, a tree view on the left to group tasks, and a zoom feature for adjusti ...

Tips for preventing the occurrence of the $digest already in progress error

I am experiencing an issue in my AngularJS application with the following code snippets: getGridPage('api/accounts/gettransactions') //$http call to server which sets the $scope $scope.transactions = {} The error message "$digest already in pro ...

Turn off Typescript compilation in Visual Studio for a webpage

My Angular website (not a computer science project) is integrated into a solution, causing Visual Studio 2019 to generate multiple TypeScript compilation errors while working on other projects within the same solution. You can see examples of these errors ...

What are the appropriate levels of access that an operating system should provide for web-based scripting?

Contemplating the level of access web-based applications have to an operating system has been on my mind. I'm pondering: What is the most effective method for determining this currently? Are we seeing a trend towards increased or decreased access? ...

How can we transfer parameters in JavaScript?

My vision may be a bit vague, but I'll try to explain it as best as I can. I want to implement multiple buttons that can toggle the visibility of a div (I have this functionality working already). Each button should carry two values (a number and a l ...

Trouble with displaying canvas images in imageDraw() function

I'm having trouble with my Imagedraw() method when trying to obtain image data using toDataURL(). var video = document.getElementById('media-video'); var videoCurrentTime = document.getElementById('media-video').currentTime; var ...

How can I integrate Cheerio.js into an Angular 6 application?

Recently, I embarked on a new Angular 6 project where I decided to incorporate Cheerio.js. To do so, I first ran the command: npm install cheerio Once I had successfully installed Cheerio.js, I proceeded to import it into my project and add it to the NgM ...

Is it possible to pass image data response from jQuery .ajax into a new AJAX call?

Currently, I am attempting to combine the ImageOptim API with the OCR.space API. Both APIs are exceptional, and I cannot recommend them highly enough! However, a challenge arises as the OCR API only accepts images under 1mb or 2600x2600 px in the free tier ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

JQuery UI Autocomplete - Issue with loading data object

I've been attempting to implement autocomplete with JQuery UI, but I'm encountering difficulties when passing in a label & value object. var individuals = []; var test = new Array(); var dataObject = jQuery.parseJSON(data) ...

How can we make sure the selected tab opens in jQuery tabbed content?

I'm trying to make my tabbed content open on a specific tab by changing the URL. I remember seeing something like this before but can't seem to find it! Here's the fiddle I created: http://jsfiddle.net/sW966/ Currently, the default tab is ...

Is there a way to reset the yAxes count of a chart.js chart in Angular when changing tabs?

I am currently using chart.js within an Angular framework to visually display data. Is there any method available to reset the y-axis data when changing tabs? Take a look at this Stackblitz demo for reference. Upon initial loading of the page, the data ...