Skip to content

Commit ab3ed5a

Browse files
committed
feat: Add preload() method to lazy
1 parent 0847cef commit ab3ed5a

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/lazy.d.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { ComponentChildren, VNode } from 'preact';
22

3-
export default function lazy<T>(load: () => Promise<{ default: T } | T>): T;
3+
export default function lazy<T>(load: () => Promise<{ default: T } | T>): T & {
4+
preload: () => Promise<T>;
5+
};
46

57
export function ErrorBoundary(props: { children?: ComponentChildren; onError?: (error: Error) => void }): VNode;

src/lazy.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,25 @@ import { useState, useRef } from 'preact/hooks';
33

44
export default function lazy(load) {
55
let p, c;
6-
return props => {
6+
7+
const loadModule = () =>
8+
load().then(m => (c = (m && m.default) || m));
9+
10+
const LazyComponent = props => {
711
const [, update] = useState(0);
812
const r = useRef(c);
9-
if (!p) p = load().then(m => (c = (m && m.default) || m));
13+
if (!p) p = loadModule();
1014
if (c !== undefined) return h(c, props);
1115
if (!r.current) r.current = p.then(() => update(1));
1216
throw p;
1317
};
18+
19+
LazyComponent.preload = () => {
20+
if (!p) p = loadModule();
21+
return p;
22+
}
23+
24+
return LazyComponent;
1425
}
1526

1627
// See https://github.com/preactjs/preact/blob/88680e91ec0d5fc29d38554a3e122b10824636b6/compat/src/suspense.js#L5

0 commit comments

Comments
 (0)