Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to get the current date and time in seconds ?
Next article icon

How to Get Page Load Time in Angular?

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In web development, performance is the most important thing. Users expect fast and responsive web applications and even minor delays can impact user experience and satisfaction. Monitoring page load time is important for identifying performance bottlenecks and optimizing the user experience. In this article, we'll explore how to get page load time in Angular 15.

Prerequisites

  • NodeJs
  • Angular Js
  • Typescript

What is Page Load Time?

Page load time, also known as page load speed, refers to the time it takes for a web page to fully load in a user's browser. It includes the time taken to fetch and render all the necessary resources, such as HTML, CSS, JavaScript, images, and other assets. Measuring page load time provides valuable insights into the performance of web applications and helps identify areas for improvement.

Approach

  • We will create a component, interceptor, module and routing module files.
  • In the routing module, we will add our routing for all components. We will register the components, modules and interceptors in the module file.
  • We will create app component and in the app component, we will capture the routing events with angular router NavigationStart and NavigationEnd. The app component is our base component and the routing for all the component will be shown through the app component.
  • Therefore, any redirection to page the routing event will trigger and events will be captured in the app component. We will log the routing time, store it in the variable and render in the HTML. You can find the code later.
  • We will create HTTP interceptor to capture API loading time. Therefore, whenever HTTP request hits, It will go through the interceptor and will capture the API loading time by start and end.

Steps to Get page Load Time

Step 1: Install Angular CLI

  • First you need to install Node.js on your system.
  • Second, open your terminal or CMD(Command prompt) and run the below command
npm install -g @angular/cli

Step 2: Create a new Angular application

Run the below command to create a new Angular application

ng new angular-api-routing-time

Step 3: Redirect to project directory

Change you working directory by entering project name in the below command

cd angular-api-routing-time

Step 4: Execute an application

ng serve --open

The --open flag open an application directly in a browser. The application default run on http://localhost:4200.

After completing project creation and setup, you need create Components, Service, Module and Interceptor and the structure will be display like the below image.

Step 5: Create component

ng generate component home ng g c about

The above command will create a component in the app directory. You can shorthand the command by writing ng g c.

Step 6: Create interceptors

ng generate interceptor application

The above command will create interceptor in the app directory.

Step 7: Create Module with Routing

ng generate module app --routing

The above command will generate module with routing. Here it will generate app.module.ts and app-routing.module.ts.

Folder Structure

project-tree
Folder Structure

Dependencies

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Example

JavaScript
//app.module.ts  import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { CommonModule } from '@angular/common'; import { AppComponent } from './app.component'; import { ApplicationInterceptor } from './_interceptor/application.interceptor'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module';  @NgModule({     declarations: [AppComponent],     imports: [         BrowserModule,         CommonModule,         AppRoutingModule,     ],     providers: [         {             provide: HTTP_INTERCEPTORS,             useClass: ApplicationInterceptor,             multi: true,         },     ],     bootstrap: [AppComponent], }) export class AppModule { } 
JavaScript
//app.component.ts  import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; import { Router, NavigationStart, NavigationEnd } from '@angular/router';  @Component({     selector: 'app-root',     template: `     <h1>Angular Routing and API Load Timing</h1>     <nav><a routerLink="">Home</a> | <a routerLink="/about">About</a></nav>     <router-outlet></router-outlet>     <p>       <span style="color: #333333; font-weight: bold; font-size: 20px">         Navigation time:       </span>       <span style="color: #ff2222; font-weight: bold; font-size: 20px"         >{{ this.routingTotal }} ms</span       >     </p>   `,     styleUrl: './app.component.css', }) export class AppComponent implements OnInit, OnDestroy {     title = 'angular-api-time-routing';     routerSubscription!: Subscription;     routingStart!: number | null;     routingEnd!: number | null;     routingTotal!: number | null;      constructor(private router: Router) { }      ngOnInit(): void {         this.routerSubscription = this.router.events.subscribe((event) => {             if (event instanceof NavigationStart) {                 this.routingStart = performance.now();                 this.routingEnd = null;             } else if (event instanceof NavigationEnd) {                 this.routingEnd = performance.now();                 if (this.routingStart !== null) {                     this.routingTotal = this.routingEnd - this.routingStart;                     console.log(                         `%c Navigation time: %c ${this.routingEnd - this.routingStart} ms`,                         `color: #CCCCCC; font-weight: bold; font-size: 20px`,                         `color: #ff2222; font-weight: bold; font-size: 20px`                     );                 }             }         });     }      ngOnDestroy() {         if (this.routerSubscription) {             this.routerSubscription.unsubscribe();             console.log('clear');         }     } } 
JavaScript
//app-routing.module.ts  import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component';  const routes: Routes = [     { path: '', component: HomeComponent, pathMatch: 'full' },     { path: 'about', component: AboutComponent }, ];  @NgModule({     imports: [RouterModule.forRoot(routes)],     exports: [RouterModule], }) export class AppRoutingModule { } 
JavaScript
//application.interceptor.ts  import { Injectable } from '@angular/core'; import {     HttpInterceptor,     HttpRequest,     HttpHandler,     HttpEvent, } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators';  @Injectable() export class ApplicationInterceptor implements HttpInterceptor {      intercept(         httpReq: HttpRequest<any>,         httpNext: HttpHandler     ): Observable<HttpEvent<any>> {          const apiStart = performance.now();          return httpNext.handle(httpReq).pipe(             tap(() => {                 const apiEnd = performance.now();                 console.log(                     `%c API req name: %c ${httpReq.url},                      %c API time: %c ${apiEnd - apiStart                     } ms`,                     `color: #CCCCCC; font-weight: bold; font-size: 20px`,                     `color: #ff2222; font-weight: bold; font-size: 20px`,                     `color: #CCCCCC; font-weight: bold; font-size: 20px`,                     `color: #ff2222; font-weight: bold; font-size: 20px`                 );             })         );     } } 

Output

time-frame-new
How to Get Page Load Time in Angular?

The above example shows how to capture page load time including API calls after routing to a new URL.


Next Article
How to get the current date and time in seconds ?

R

raviashar
Improve
Article Tags :
  • Web Technologies
  • AngularJS
  • AngularJS-Questions

Similar Reads

  • How to get the value of the form in Angular ?
    In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object. Syntax: form.value Return Value: object: It is an object containing form value Approach:  Create the Angular app to be usedIn app.componen
    1 min read
  • How to Create a new module in Angular ?
    Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
    3 min read
  • How to Get All Route Params/Data in Angular?
    In Angular, managing route parameters and extracting data from routes is important for creating dynamic and responsive web applications. Route parameters allow you to pass information in URLs, and accessing this data enables your application to make decisions and render content dynamically. This art
    4 min read
  • How to get the current date and time in seconds ?
    In this article, we will learn how to get the current date & time in seconds using JavaScript build-in methods. We will perform it in 2 ways: Using Date.now() methodUsing new Date.getTime() methodMethod 1: Using Date.now() MethodThe Date.now() method returns the number of milliseconds elapsed si
    2 min read
  • How to Use the Async Pipe in Angular?
    The AsyncPipe in Angular is a powerful and convenient tool used to handle asynchronous data streams such as observables and promises directly in the component template. It automatically subscribes to observables, renders their values, and updates the view when new data is emitted. This removes the n
    3 min read
  • How to Get Current Time in JavaScript ?
    This article will show you how to get the current time in JavaScript. Whether you are creating a digital clock, scheduling events, or simply logging timestamps, knowing how to retrieve the current time is essential. Here, we will cover different methods to get the current time in JavaScript. Table o
    3 min read
  • How To Use OnChanges In Angular?
    Angular is a powerful framework for building dynamic web applications, and one of its core features is the ability to manage and react to changes in component data. One of the key lifecycle hooks in Angular for responding to changes in input properties is the OnChanges lifecycle hook. This hook is h
    3 min read
  • How to detect a route change in AngularJS ?
    In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
    2 min read
  • How Single Page Applications work in Angular ?
    In traditional web applications, each time a user interacts with a website, the server sends a new HTML page back to the browser. This process can be slow and inefficient, resulting in a less-than-optimal user experience. Single Page Applications (SPAs) solve this problem by loading all necessary re
    7 min read
  • How to pick which Angular Bundle to Preload ?
    Loading strategy in angular decides how to load the app modules when the application runs into the browser. In Angular, we have three types of loading: Eager loading, lazy loading, and preloading. By default, Angular follows eager loading i.e. as soon as the application starts downloading in the bro
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences