perf: load page modules on demand and avoid repeated startup ACL writes

This commit is contained in:
abaishu0730 committed 2026-10-28 15:20:28 +08:00
1 parent 73773f9526
commit 7ead1e7cb7
19 files changed
+330 -24

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
'use strict';
window.AppModules=(()=>{
const manifest=JSON.parse(document.querySelector('meta[name="app-modules"]')?.content||'{}');
const groups=manifest.groups||{},urls=manifest.urls||{},loaded=new Map(),preloads=new Map();
function assetFor(route){
const src=urls['/'+route];
if(typeof src!=='string'||!/^\/(?!\/)[\w./-]+\.js\?v=[a-f0-9]{64}$/.test(src))throw Error('页面资源版本无效,请重新加载工作台。');
const hash=src.slice(src.lastIndexOf('=')+1),integrity='sha256-'+btoa(String.fromCharCode(...hash.match(/../g).map(byte=>parseInt(byte,16))));
return {src,integrity};
}
function preload(asset){
if(loaded.has(asset.src)||preloads.has(asset.src))return;
const link=document.createElement('link');link.rel='preload';link.as='script';link.href=asset.src;link.integrity=asset.integrity;link.crossOrigin='anonymous';preloads.set(asset.src,link);document.head.appendChild(link);
}
function loadOne(route,asset){
const {src,integrity}=asset;
if(loaded.has(src))return loaded.get(src);
const script=document.createElement('script');script.async=true;script.src=src;script.integrity=integrity;script.crossOrigin='anonymous';
const promise=new Promise((resolve,reject)=>{script.onload=resolve;script.onerror=()=>reject(Error('无法加载页面资源:/'+route));});
loaded.set(src,promise);
document.head.appendChild(script);
promise.catch(()=>{if(loaded.get(src)===promise){loaded.delete(src);script.remove();}});
const cleanup=()=>{preloads.get(src)?.remove();preloads.delete(src);};promise.then(cleanup,cleanup);
return promise;
}
function filesFor(route,parents=new Set()){
if(parents.has(route)||!Object.hasOwn(groups,route))throw Error('页面模块配置无效,请重新加载工作台。');
const next=new Set(parents).add(route);
return groups[route].flatMap(item=>item.startsWith('$')?filesFor(item,next):[item]);
}
async function load(route){
const files=[...new Set(filesFor(route))].map(file=>({file,asset:assetFor(file)}));
// Download dependencies together, but execute only this route's sequence.
// A stalled script from an abandoned route cannot block another route.
for(const {asset} of files)preload(asset);
try{for(const {file,asset} of files)await loadOne(file,asset);}
finally{for(const {asset} of files){preloads.get(asset.src)?.remove();preloads.delete(asset.src);}}
}
return {load};
})();