Improve screen cache service
This commit is contained in:
parent
1ee156b2c5
commit
fc11a44ec9
|
@ -1,23 +1,37 @@
|
||||||
import { Injectable, NgZone } from '@angular/core'
|
import { Injectable } from '@angular/core'
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ScreenService {
|
export class ScreenService {
|
||||||
private windowInnerWidth: number
|
private windowInnerWidth: number
|
||||||
|
private lastFunctionCallTime: number
|
||||||
|
private cacheForMs = 500
|
||||||
|
|
||||||
constructor (private zone: NgZone) {
|
constructor () {
|
||||||
this.windowInnerWidth = window.innerWidth
|
this.refreshWindowInnerWidth()
|
||||||
|
|
||||||
// Try to cache a little bit window.innerWidth
|
|
||||||
this.zone.runOutsideAngular(() => {
|
|
||||||
setInterval(() => this.windowInnerWidth = window.innerWidth, 500)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
isInSmallView () {
|
isInSmallView () {
|
||||||
return this.windowInnerWidth < 600
|
return this.getWindowInnerWidth() < 600
|
||||||
}
|
}
|
||||||
|
|
||||||
isInMobileView () {
|
isInMobileView () {
|
||||||
return this.windowInnerWidth < 500
|
return this.getWindowInnerWidth() < 500
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache window inner width, because it's an expensive call
|
||||||
|
private getWindowInnerWidth () {
|
||||||
|
if (this.cacheWindowInnerWidthExpired()) this.refreshWindowInnerWidth()
|
||||||
|
|
||||||
|
return this.windowInnerWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
private refreshWindowInnerWidth () {
|
||||||
|
this.lastFunctionCallTime = new Date().getTime()
|
||||||
|
|
||||||
|
this.windowInnerWidth = window.innerWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
private cacheWindowInnerWidthExpired () {
|
||||||
|
return new Date().getTime() > (this.lastFunctionCallTime + this.cacheForMs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue