Skip to content

Commit

Permalink
Fixes jakubkowalczyk-pl#18: Preload images.
Browse files Browse the repository at this point in the history
Preloads the next and previous image when a user navigates to an image.
Preloading happens right after the navigation is done.

Calling load on an already loaded image will not cause the browser to
do another request, this way the method can be called multiple times
without worry.

Uses Promise.all to make sure both images get loaded as fast as
possible.
  • Loading branch information
qurben committed Feb 26, 2020
1 parent 50cdd3d commit 607f16f
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions src/gallery/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Params from './parameters';
import defaults from './defaults';
import withSlideShow from "./with-slideshow";
import withThumbnails from "./with-thumbnails";
import load from '../utils/load';

let id = 1;

Expand Down Expand Up @@ -177,32 +178,36 @@ export class Gallery extends Component {
return this.getItems().find(item => item.hash === hash);
}

protected async next(): Promise<void> {
public get nextItem() {
const { album, item } = this;
const { items } = album;
const next = items[items.indexOf(item)+1];

if (next) {
await this.goToItem(next);
}
else {
await this.goToItem(items[0]);
return next;
} else {
return items[0];
}
}

protected async prev(): Promise<void> {
protected async next(): Promise<void> {
await this.goToItem(this.nextItem);
}

public get prevItem() {
const { album, item } = this;
const { items } = album;
const prev = items[items.indexOf(item)-1];

if (prev) {
await this.goToItem(prev);
}
else {
await this.goToItem(items[items.length-1]);
return prev;
} else {
return items[items.length-1];
}
}

protected async prev(): Promise<void> {
await this.goToItem(this.prevItem);
}

private showTransitionCanvas(): void {
this.previewElement.appendChild(this.transitionCanvas.element);
}
Expand Down Expand Up @@ -270,6 +275,10 @@ export class Gallery extends Component {
resolve();
return Promise.resolve();
},
() => Promise.all([
() => this.nextItem.element ? Promise.resolve() : load(this.nextItem.url),
() => this.prevItem.element ? Promise.resolve() : load(this.prevItem.url)
]),
);

queue.run();
Expand Down

0 comments on commit 607f16f

Please sign in to comment.