Reputation: 4972
I am trying to get the time a component take to totally load into the dom, using the following inside ngOninit()
from this answer on stack:
ngOnInit()
{
var time = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart
console.log(time)
}
The result was like:
-1544706869570
I used ngAfterViewInit()
:
ngAfterViewInit(){
var time = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart
console.log(time)
}
And it was the same result.
How to transform it into seconds, and is there a better solution to heck the component load in angular 7 ?
Upvotes: 4
Views: 4096
Reputation: 757
You can measure it with window.performance.now in milliseconds like this:
startTime! : number
initTime! : number
contentInitTime! : number
viewInitTime! : number
printTime(time : number) {
console.log(`Global loading ${ time }ms`)
console.log(`Global loading ${ time / 1000 }s`)
console.log(`Component loading ${ time - this.startTime }ms`)
console.log(`Component loading ${ (time - this.startTime) / 1000 }s`)
}
// Created
constructor() {
this.startTime = window.performance.now()
this.printTime(this.startTime)
}
// Initialized by angular
ngOnInit() {
this.initTime = window.performance.now()
this.printTime(this.initTime)
}
// Rendered without children
ngAfterContentInit() {
this.contentInitTime = window.performance.now()
this.printTime(this.contentInitTime)
}
// Rendered with children
ngAfterViewInit() {
this.viewInitTime = window.performance.now()
this.printTime(this.viewInitTime)
}
Upvotes: 5