@@ -55,21 +55,24 @@ const strategies: Record<string, Strategy> = {
5555 visible
5656}
5757
58- const timers = new WeakMap < Element , number > ( )
59- function scan ( node : Element ) {
60- cancelAnimationFrame ( timers . get ( node ) || 0 )
58+ type ElementLike = Element | Document | ShadowRoot
59+
60+ const timers = new WeakMap < ElementLike , number > ( )
61+ function scan ( element : ElementLike ) {
62+ cancelAnimationFrame ( timers . get ( element ) || 0 )
6163 timers . set (
62- node ,
64+ element ,
6365 requestAnimationFrame ( ( ) => {
6466 for ( const tagName of dynamicElements . keys ( ) ) {
65- const child : Element | null = node . matches ( tagName ) ? node : node . querySelector ( tagName )
67+ const child : Element | null =
68+ element instanceof Element && element . matches ( tagName ) ? element : element . querySelector ( tagName )
6669 if ( customElements . get ( tagName ) || child ) {
6770 const strategyName = ( child ?. getAttribute ( 'data-load-on' ) || 'ready' ) as keyof typeof strategies
6871 const strategy = strategyName in strategies ? strategies [ strategyName ] : strategies . ready
6972 // eslint-disable-next-line github/no-then
7073 for ( const cb of dynamicElements . get ( tagName ) || [ ] ) strategy ( tagName ) . then ( cb )
7174 dynamicElements . delete ( tagName )
72- timers . delete ( node )
75+ timers . delete ( element )
7376 }
7477 }
7578 } )
@@ -82,17 +85,20 @@ export function lazyDefine(tagName: string, callback: () => void) {
8285 if ( ! dynamicElements . has ( tagName ) ) dynamicElements . set ( tagName , new Set < ( ) => void > ( ) )
8386 dynamicElements . get ( tagName ) ! . add ( callback )
8487
85- scan ( document . body )
88+ observe ( document )
89+ }
8690
87- if ( ! elementLoader ) {
88- elementLoader = new MutationObserver ( mutations => {
89- if ( ! dynamicElements . size ) return
90- for ( const mutation of mutations ) {
91- for ( const node of mutation . addedNodes ) {
92- if ( node instanceof Element ) scan ( node )
93- }
91+ export function observe ( target : ElementLike ) : void {
92+ elementLoader ||= new MutationObserver ( mutations => {
93+ if ( ! dynamicElements . size ) return
94+ for ( const mutation of mutations ) {
95+ for ( const node of mutation . addedNodes ) {
96+ if ( node instanceof Element ) scan ( node )
9497 }
95- } )
96- elementLoader . observe ( document , { subtree : true , childList : true } )
97- }
98+ }
99+ } )
100+
101+ scan ( target )
102+
103+ elementLoader . observe ( target , { subtree : true , childList : true } )
98104}
0 commit comments