Skip to content

Commit f6489c9

Browse files
koddssonkeithamus
andcommitted
Pass in the element tag name to strategies
Co-authored-by: Keith Cirkel <keithamus@users.noreply.github.com>
1 parent 065bde1 commit f6489c9

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

src/lazy-define.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
type Strategy = (tagName: string) => Promise<void>
2+
13
const dynamicElements = new Map<string, Set<() => void>>()
24

35
const ready = new Promise<void>(resolve => {
@@ -20,9 +22,17 @@ const firstInteraction = new Promise<void>(resolve => {
2022
document.addEventListener('pointerdown', handler, listenerOptions)
2123
})
2224

23-
const strategies = {
24-
ready,
25-
firstInteraction
25+
26+
const strategies: Record<string, Strategy> = {
27+
ready: () => ready,
28+
firstInteraction: () => firstInteraction
29+
}
30+
31+
export function addStrategy(name: string, strategy: Strategy) {
32+
if (name in strategy) {
33+
throw new Error(`Strategy ${name} already exists!`)
34+
}
35+
strategies[name] = strategy
2636
}
2737

2838
const timers = new WeakMap<Element, number>()
@@ -37,7 +47,7 @@ function scan(node: Element = document.body) {
3747
const strategyName = (child?.getAttribute('data-load-on') || 'ready') as keyof typeof strategies
3848
const strategy = strategyName in strategies ? strategies[strategyName] : strategies.ready
3949
// eslint-disable-next-line github/no-then
40-
for (const cb of dynamicElements.get(tagName) || []) strategy.then(cb)
50+
for (const cb of dynamicElements.get(tagName) || []) strategy(tagName).then(cb)
4151
dynamicElements.delete(tagName)
4252
timers.delete(node)
4353
}

0 commit comments

Comments
 (0)