Fix page loader: execute inline scripts, JS module loading optional

- innerHTML strips script tags, now extract and eval them
- External .js module: 404 = skip gracefully (no error)
- Progress bar: completes regardless of JS module
- Proxy/projects pages now render with CSS + inline JS executes
This commit is contained in:
qinglong
2026-06-11 14:43:24 +08:00
parent dd8a31e29a
commit c07cea4ff7
3 changed files with 31 additions and 26 deletions
+29 -24
View File
@@ -43,35 +43,40 @@ async function loadPage(pageName) {
await new Promise(r => requestAnimationFrame(() => { bar.style.width = '80%'; setTimeout(r, 100); }));
try {
// 🟢 关键修改:fetch 路径必须包含 /static/
const html = await fetch(`./static/pages/${pageName}.html`).then(r => {
if(!r.ok) throw new Error('404');
return r.text();
const resp = await fetch(`./static/pages/${pageName}.html`);
if(!resp.ok) throw new Error('404');
const html = await resp.text();
// Extract inline scripts before innerHTML (browsers skip them)
const scripts = [];
const cleanHtml = html.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi, (m, code) => {
scripts.push(code.trim()); return '';
});
content.innerHTML = html;
// 动态加载对应 JS 模块
// 🟢 关键修改:script src 路径必须包含 /static/
const script = document.createElement('script');
script.src = `./static/pages/${pageName}.js?t=${Date.now()}`;
script.onload = () => {
// 触发模块初始化
const moduleName = pageName.charAt(0).toUpperCase() + pageName.slice(1) + 'Module';
if(window[moduleName]?.init) {
window[moduleName].init();
content.innerHTML = cleanHtml;
// Execute inline scripts
for(const code of scripts) {
try { (new Function(code)).call(window); } catch(e) { console.error('Inline script error:', e); }
}
// Load external JS module (optional — skip if 404)
try {
const jsResp = await fetch(`./static/pages/${pageName}.js?t=${Date.now()}`);
if(jsResp.ok) {
const jsCode = await jsResp.text();
(new Function(jsCode)).call(window);
const moduleName = pageName.charAt(0).toUpperCase() + pageName.slice(1) + 'Module';
if(window[moduleName]?.init) window[moduleName].init();
}
bar.style.width = '100%';
setTimeout(() => bar.classList.remove('active'), 200);
};
script.onerror = () => {
throw new Error('JS Load Failed');
};
document.head.appendChild(script);
} catch(e) { /* JS module optional */ }
bar.style.width = '100%';
setTimeout(() => bar.classList.remove('active'), 200);
} catch(e) {
content.innerHTML = `<div style="color:var(--error); text-align:center; margin-top:20vh;">页面加载失败: ${e.message}</div>`;
bar.style.background = 'var(--error)';
setTimeout(() => { bar.style.width = '100%'; setTimeout(() => { bar.classList.remove('active'); bar.style.background = 'var(--accent)'; }, 200); }, 100);
setTimeout(() => { bar.style.width = '100%'; setTimeout(() => { bar.classList.remove('active'); bar.style.background = 'var(--primary)'; }, 200); }, 100);
}
}