之前说了笔者写了一个微前端框架。在微前端中子应用切换前要先获取到子应用的资源(比如js、css)和 html 片段进行加载。那么这里就涉及到一个“老生常谈”的话题:资源缓存。
为了缓存子应用的 js、css资源,笔者分两步进行:首先是在主应用加载时“预加载”子应用:
export const prefetch = async () => {
// 获取到所有子应用的列表,但不包括当前正在显示的
const list = getList().filter(item => !window.location.pathname.startsWith(item.activeRule))
// 预加载剩下的所有子应用
await Promise.all(list.map(async item => await parseHtml(item.entry, item.name)))
}
然后是在资源请求前后判断缓存、存入缓存:
const cache = {} //根据子应用的name做缓存
export const parseHtml = async (entry, name) => {
if(cache[name]) {
return cache[name]
}
// 资源加载其实是一个get请求,我们去模拟这个过程
const html = await fetchResource(entry)
let allScripts = []
//...
// 抽离标签、link、script(src、代码)
const [dom, scriptUrl, script] = await getResources(div, entry)
// 获取所有的js资源
const fetchedScripts = await Promise.all(scriptUrl.map(async item => await fetchResource(item)))
allScripts = script.concat(fetchedScripts)
cache[name] = [dom, allScripts]
//...
}
这样就达到了提高响应速度的效果。