MCPcopy Index your code
hub / github.com/1Panel-dev/MaxKB / loadScript

Function loadScript

ui/src/utils/common.ts:117–162  ·  view source on GitHub ↗
(url: string, options: LoadScriptOptions = {})

Source from the content-addressed store, hash-verified

115}
116
117export const loadScript = (url: string, options: LoadScriptOptions = {}): Promise<void> => {
118 const { jsId, forceReload = false } = options;
119 const scriptId = jsId || `script-${btoa(url).slice(0, 12)}`;
120
121 const cleanupScript = (script: HTMLScriptElement) => {
122 if (script && script.parentElement) {
123 script.parentElement.removeChild(script);
124 }
125 };
126
127 return new Promise((resolve, reject) => {
128 if (typeof document === 'undefined') {
129 reject(new Error('Cannot load script in non-browser environment'));
130 return;
131 }
132
133 const existingScript = document.getElementById(scriptId) as HTMLScriptElement | null;
134
135 if (existingScript && !forceReload) {
136 if (existingScript.src === url) {
137 console.log(`[loadScript] Reuse existing script: ${url}`);
138 resolve();
139 return;
140 }
141 existingScript.remove();
142 }
143
144 const script = document.createElement('script');
145 script.id = scriptId;
146 script.src = url;
147 script.async = true;
148
149 script.onload = () => {
150 console.log(`[loadScript] Script loaded: ${url}`);
151 resolve();
152 };
153
154 script.onerror = () => {
155 console.error(`[loadScript] Failed to load: ${url}`);
156 cleanupScript(script);
157 reject(new Error(`Failed to load script: ${url}`));
158 };
159
160 document.head.appendChild(script);
161 });
162};
163
164// 清理脚本(可选)
165const cleanupScript = (script: HTMLScriptElement) => {

Callers

nothing calls this directly

Calls 3

cleanupScriptFunction · 0.85
logMethod · 0.80
errorMethod · 0.45

Tested by

no test coverage detected