Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: do not run change detection on resize events #779

Merged
merged 1 commit into from
May 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 35 additions & 25 deletions src/app/pdf-viewer/pdf-viewer.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import {
OnChanges,
SimpleChanges,
OnInit,
HostListener,
OnDestroy,
ViewChild,
AfterViewChecked
AfterViewChecked,
NgZone
} from '@angular/core';
import { from, fromEvent, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { debounceTime, filter, takeUntil } from 'rxjs/operators';
import * as PDFJS from 'pdfjs-dist';
import * as PDFJSViewer from 'pdfjs-dist/web/pdf_viewer';

Expand Down Expand Up @@ -216,7 +216,7 @@ export class PdfViewerComponent
return null;
}

constructor(private element: ElementRef) {
constructor(private element: ElementRef<HTMLElement>, private ngZone: NgZone) {
if (isSSR()) {
return;
}
Expand Down Expand Up @@ -253,18 +253,15 @@ export class PdfViewerComponent
this.isVisible = true;

setTimeout(() => {
this.ngOnInit();
this.initialize();
this.ngOnChanges({ src: this.src } as any);
});
}
}

ngOnInit() {
if (!isSSR() && this.isVisible) {
this.isInitialized = true;
this.setupMultiPageViewer();
this.setupSinglePageViewer();
}
this.initialize();
this.setupResizeListener();
}

ngOnDestroy() {
Expand All @@ -273,21 +270,6 @@ export class PdfViewerComponent
this.loadingTask = null;
}

@HostListener('window:resize', [])
public onPageResize() {
if (!this._canAutoResize || !this._pdf) {
return;
}

if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}

this.resizeTimeout = window.setTimeout(() => {
this.updateSize();
}, 100);
}

get pdfLinkService(): any {
return this._showAll
? this.pdfMultiPageLinkService
Expand Down Expand Up @@ -674,4 +656,32 @@ export class PdfViewerComponent
this.pdfSinglePageLinkService.setDocument(this._pdf, null);
}
}

private initialize(): void {
if (isSSR() || !this.isVisible) {
return;
}

this.isInitialized = true;
this.setupMultiPageViewer();
this.setupSinglePageViewer();
}

private setupResizeListener(): void {
if (isSSR()) {
return;
}

this.ngZone.runOutsideAngular(() => {
fromEvent(window, 'resize')
.pipe(
debounceTime(100),
filter(() => this._canAutoResize && !!this._pdf),
takeUntil(this.destroy$)
)
.subscribe(() => {
this.updateSize();
});
});
}
}