2

I am trying to report page load times to google analytics in my Angular 15 app. As far as I can tell, the only way to accurately measure the page load time is by using the AfterViewInit lifecycle hook. This works great, but I refuse to add it to all 100+ pages in the app, and I don't want to forget to add it to new pages in the future. So I would like to be able to subscribe to a components lifecycle hooks programmatically.

The best solutions I've found so far are @mixins and extending a base class, but again, I don't want to modify every page.

I am able to get a reference to the loaded component with the following code in my app's root component, I am hoping there is some library or utility I can use to then hook into the component's lifecycle.

this.router.events.pipe(
    tap((e: any) => {
        if (e instanceof ActivationEnd) {
            console.log("ActivationEnd", e.snapshot.component)
        }
    })
);

There might be a better way to achieve the same functionality. I've tried the following, but it only works on initial page load, and seems to be unreliable at best.

document.onreadystatechange = function () {
    console.log('document.readyState', document.readyState)
}

I've also tried using NgZone but it is reporting the page is fully loaded 10+ seconds after it appears to be.

Everything else I've tried (NavigationEnd, canActivateChild, etc) is firing far too early.

2
  • what if you try to catch first zone stable event after navigationEnd? Commented Mar 1, 2024 at 1:17
  • Maybe write a method decorator? You will still need to change every class, but it would be easy here to run a replaceAll over the project to reduce the workload of this step Commented Mar 1, 2024 at 7:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.