1- import { computed , type ComputedRef , type Directive } from "vue" ;
1+ import { computed , nextTick , type ComputedRef , type Directive } from "vue" ;
22
33export function debounceComputed < T > ( func : ( ) => T , wait = 1000 ) : ComputedRef < T > {
44 let lastCacheTime = Date . now ( ) ;
@@ -19,14 +19,56 @@ export function debounceComputed<T>(func: () => T, wait = 1000): ComputedRef<T>
1919 } ) ;
2020}
2121
22+ async function execScript ( scr : HTMLScriptElement , shadowRoot : ShadowRoot ) {
23+ let text = scr . textContent ;
24+ if ( scr . src ) {
25+ const fe = await fetch ( scr . src ) ;
26+ if ( ! fe . ok ) throw new Error ( 'Failed to fetch script' ) ;
27+ text = await fe . text ( ) ;
28+ }
29+ const script = document . createElement ( 'script' ) ;
30+ script . textContent = text ;
31+ shadowRoot . appendChild ( script ) ;
32+ }
33+
34+ function handleShadow ( el : HTMLElement ) {
35+ requestAnimationFrame ( async ( ) => {
36+ const scrs = el . shadowRoot ?. querySelectorAll ( 'script' ) ;
37+ // @ts -ignore store
38+ el . hasScript = ! ! scrs ?. length ;
39+
40+ // render script
41+ const defer = [ ] as HTMLScriptElement [ ] ;
42+ for ( const scr of scrs || [ ] ) {
43+ // defer: exec script after dom render
44+ if ( scr . defer ) defer . push ( scr ) ;
45+
46+ // async: create async corutine to exec script
47+ if ( scr . async ) execScript ( scr , el . shadowRoot ! ) ;
48+
49+ // exec script immediately
50+ await execScript ( scr , el . shadowRoot ! ) ;
51+ }
52+
53+ // exec deferred script
54+ for ( const scr of defer ) execScript ( scr , el . shadowRoot ! ) ;
55+ } ) ;
56+ }
57+
2258export const vRender : Directive < HTMLElement , string > = {
2359 mounted ( el , binding ) {
2460 el . shadowRoot || el . attachShadow ( { mode : 'open' } ) ;
2561 el . shadowRoot ! . innerHTML = binding . value ;
62+
63+ handleShadow ( el ) ;
2664 } ,
2765
2866 updated ( el , binding ) {
67+ // @ts -ignore store
68+ if ( el . hasScript ) location . reload ( ) ; // prevent JS leak
2969 el . shadowRoot ! . innerHTML = binding . value ;
70+
71+ handleShadow ( el ) ;
3072 }
3173}
3274
0 commit comments