Blog/wwwroot/Blog.lib.module.js 2 K · 83 lines · raw · history

1 const pageScriptInfoBySrc = new Map();
2
3 function registerPageScriptElement(src) {
4 if (!src) {
5 throw new Error('Must provide a non-empty value for the "src" attribute.');
6 }
7
8 let pageScriptInfo = pageScriptInfoBySrc.get(src);
9
10 if (pageScriptInfo) {
11 pageScriptInfo.referenceCount++;
12 } else {
13 pageScriptInfo = { referenceCount: 1, module: null };
14 pageScriptInfoBySrc.set(src, pageScriptInfo);
15 initializePageScriptModule(src, pageScriptInfo);
16 }
17 }
18
19 function unregisterPageScriptElement(src) {
20 if (!src) {
21 return;
22 }
23
24 const pageScriptInfo = pageScriptInfoBySrc.get(src);
25
26 if (!pageScriptInfo) {
27 return;
28 }
29
30 pageScriptInfo.referenceCount--;
31 }
32
33 async function initializePageScriptModule(src, pageScriptInfo) {
34 if (src.startsWith("./")) {
35 src = new URL(src.substring(2), document.baseURI).toString();
36 }
37
38 const module = await import(src);
39
40 if (pageScriptInfo.referenceCount <= 0) {
41 return;
42 }
43
44 pageScriptInfo.module = module;
45 module.onLoad?.();
46 module.onUpdate?.();
47 }
48
49 function onEnhancedLoad() {
50 for (const [src, { module, referenceCount }] of pageScriptInfoBySrc) {
51 if (referenceCount <= 0) {
52 module?.onDispose?.();
53 pageScriptInfoBySrc.delete(src);
54 }
55 }
56
57 for (const { module } of pageScriptInfoBySrc.values()) {
58 module?.onUpdate?.();
59 }
60 }
61
62 export function afterWebStarted(blazor) {
63 console.log("afterWebStarted");
64 customElements.define('page-script', class extends HTMLElement {
65 static observedAttributes = ['src'];
66
67 attributeChangedCallback(name, oldValue, newValue) {
68 if (name !== 'src') {
69 return;
70 }
71
72 this.src = newValue;
73 unregisterPageScriptElement(oldValue);
74 registerPageScriptElement(newValue);
75 }
76
77 disconnectedCallback() {
78 unregisterPageScriptElement(this.src);
79 }
80 });
81
82 blazor.addEventListener('enhancedload', onEnhancedLoad);
83 }