Repository navigation
fix(wujie-core): 按 href 去重入口 HTML 与动态 preload 的 stylesheet - #1109
Conversation
Skip inserting a second style when the same href was already inlined from the entry HTML or a prior dynamic placeholder. Still dispatch load on the original link so Vite preload can settle. close Tencent#1108
Dispatching load synchronously inside the hijacked appendChild loses the event
when the consumer registers its listener only after appendChild returns. Vite's
preload helper appends the link first and calls addEventListener("load") second,
so its promise never settled and the lazily imported chunk never executed.
Dispatch in a macrotask instead. Covered by two unit cases: a listener attached
after the dispatch still receives load, and nothing is dispatched in the same tick.
Normalize hrefs before comparing so query encodings still match, escape the embed attribute, and dispatch error when a failed entry style is empty.
yiludege
left a comment
There was a problem hiding this comment.
#1108 这条路径是对的:入口 HTML 把 CSS 转成 <style> 时没有 data-wujie-css-href,动态 loadStyleSheet 插入前也不查已有节点,Vite 8 的 __vite__mapDeps 会再插一份。给入口 style 写上同一查找键,命中后不再插第二份,并用 setTimeout(0) 补 load,能对上 Vite 在 appendChild 返回后才监听 load 的顺序。data-wujie-css-pending 用来区分「还在拉」和「已经失败的空 style」,这个区分是需要的。
合之前还有两处行为需要收一下:
- 已有 style 仍带着
data-wujie-css-pending时,现在会立刻派发load。第二份动态 link 会在 CSS 写入前就被当成加载成功,preload 后面的 chunk 会提前执行。pending 时应等原来的那次请求结束再派发,不要在去重命中时直接load。 - 请求成功但内容为空时,pending 被去掉,
textContent也是空,后面的查找会把它当成失败并派发error。空 CSS 文件会被误判。
单测覆盖的是 findStyleByCssHref / dispatchStyleSheetLoadAsync,没有打到 appendChild 劫持本身。这个分支上 PR Tests 也没有报结果。主路径先不动方向,上面两点收掉再看合入。
A duplicate link waits for the in-flight request. It no longer receives load while the placeholder is pending. Empty successful CSS is marked loaded, so a later lookup does not treat it as a failed entry style.
|
这两点都收了,已推到 a50307a。
单测补了这三条 |
样式请求失败时 fetchAssets 也返回空串,空文件与请求失败无法区分。 原先入口为空的 style 会被标成 error,后来的动态 link 命中后收到 error, Vite preload 随之报错,动态 import 的 chunk 不再执行。 - 命中有内容的样式才去重并补发 load;pending 时排队等待原请求结果 - 已有样式都为空时不复用,按原流程重新请求并打印 warn,请求失败的情况可以恢复 - 去掉 data-wujie-css-state 及入口的 failed 判断 Co-authored-by: Cursor <cursoragent@cursor.com>
|
感谢跟进!pending 排队这一点已经验证没问题。我在这个分支上追加了一个提交(f05e5a3),处理空样式的判断。 问题:CSS 的 调整:
验证:
|
Checklist
npm run test通过说明:已添加
packages/wujie-core/__test__/unit/css-href-dedupe.test.ts(5 项,其中「命中去重后的 load 派发时机」2 项为本次补充);本地jest -c __test__/unit/jest.config.js21 suites / 99 tests 通过。未跑 puppeteer 集成测试。未改文档站。详细描述
<style>时写入data-wujie-css-href。loadStyleSheet插入前按该属性和注释/* href */查找;命中则不再插入第二份 style,改为异步(setTimeout(..., 0))对原link派发load。消费方是在appendChild返回之后才addEventListener("load"),在调用栈内同步派发会丢事件,导致 Vite preload 的 promise 不落定、动态 import 的 chunk 不执行。data-wujie-css-href。<link>中,又被__vite__mapDepspreload 时,避免两份 style 导致后插入的默认宽高盖住原子类。最小复现:https://github.com/KeyToLove/wujie-vite8-css-dup-demo