From b4b5f3279ee136acc3ef2c3aa9a733d6a86e584f Mon Sep 17 00:00:00 2001
From: KeyToLove <370621755@qq.com>
Date: Sat, 12 Sep 2026 15:33:42 +0800
Subject: [PATCH 1/5] fix(wujie-core): dedupe stylesheet by href across html
embed and preload
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 #1108
---
.../__test__/unit/css-href-dedupe.test.ts | 36 +++++++++++++++++++
packages/wujie-core/src/effect.ts | 30 +++++++++++++++-
packages/wujie-core/src/entry.ts | 2 +-
3 files changed, 66 insertions(+), 2 deletions(-)
create mode 100644 packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
new file mode 100644
index 000000000..674396de8
--- /dev/null
+++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
@@ -0,0 +1,36 @@
+/**
+ * 入口 HTML 已将 CSS 转成 style 后,动态再插入同 href 的 link 不应再生成第二份 style。
+ * 仍需对原 link 派发 load,避免 Vite preload 一直等待。
+ */
+
+export {};
+
+const { findStyleByCssHref } = require("../../src/effect");
+
+const HREF = "https://cdn.example.com/assets/shared.css";
+const CSS = ".box{width:100%;height:100%}";
+
+describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", () => {
+ afterEach(() => {
+ document.head.innerHTML = "";
+ });
+
+ it("能匹配带 data-wujie-css-href 的入口 style", () => {
+ document.head.innerHTML = ``;
+ const found = findStyleByCssHref(document, HREF);
+ expect(found).not.toBeNull();
+ expect(found.getAttribute("data-wujie-css-href")).toBe(HREF);
+ });
+
+ it("没有属性时能匹配注释开头的旧入口 style", () => {
+ document.head.innerHTML = ``;
+ const found = findStyleByCssHref(document, HREF);
+ expect(found).not.toBeNull();
+ expect(found.textContent.indexOf(`/* ${HREF} */`)).toBe(0);
+ });
+
+ it("不同 href 不应命中", () => {
+ document.head.innerHTML = ``;
+ expect(findStyleByCssHref(document, "https://cdn.example.com/assets/other.css")).toBeNull();
+ });
+});
diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts
index de0acdef6..d64f63e3e 100644
--- a/packages/wujie-core/src/effect.ts
+++ b/packages/wujie-core/src/effect.ts
@@ -264,6 +264,27 @@ export function deferStyleSheetByHref(opts: {
}, DEFER_STYLE_HREF_TIMEOUT);
}
+function cssHrefLookupValue(href: string): string {
+ return String(href).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+}
+
+/**
+ * 按绝对 href 查找已转换的样式。
+ * 优先匹配动态占位和入口 HTML 写入的 data-wujie-css-href;
+ * 没有该属性时,兼容旧的注释形态:style 文本以 `/* href *\/` 开头。
+ */
+export function findStyleByCssHref(doc: Document | null, href: string): HTMLStyleElement | null {
+ if (!href || !doc) return null;
+ const marked = doc.querySelector(`style[data-wujie-css-href="${cssHrefLookupValue(href)}"]`);
+ if (marked) return marked as HTMLStyleElement;
+ const styles = doc.querySelectorAll("style");
+ for (let i = 0; i < styles.length; i++) {
+ const text = styles[i].textContent || "";
+ if (text.indexOf(`/* ${href} */`) === 0) return styles[i] as HTMLStyleElement;
+ }
+ return null;
+}
+
let dynamicScriptExecStack = Promise.resolve();
function rewriteAppendOrInsertChild(opts: {
rawDOMAppendOrInsertBefore: (newChild: T, refChild?: Node | null) => T;
@@ -311,8 +332,14 @@ function rewriteAppendOrInsertChild(opts: {
const exclude = isMatchUrl(styleHref, getEffectLoaders("cssExcludes", plugins));
if (!styleHref || exclude) return;
+ // 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。
+ // 仍派发 load,避免 Vite preload 一直等待 stylesheet 的 load 事件。
+ if (findStyleByCssHref(iframeDocument, styleHref)) {
+ manualInvokeElementEvent(linkElement, "load");
+ return;
+ }
+
// 立即创建占位 `
+ : ``
);
} else if (content) {
embedHTML = embedHTML.replace(
From 450ab2fef80720a7627cdacc644fd7ff5708c75a Mon Sep 17 00:00:00 2001
From: KeyToLove <370621755@qq.com>
Date: Tue, 15 Sep 2026 19:12:03 +0800
Subject: [PATCH 2/5] fix(wujie-core): dispatch load asynchronously after
stylesheet dedupe
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.
---
.../__test__/unit/css-href-dedupe.test.ts | 41 ++++++++++++++++++-
packages/wujie-core/src/effect.ts | 15 ++++++-
2 files changed, 53 insertions(+), 3 deletions(-)
diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
index 674396de8..1b378de2c 100644
--- a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
+++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
@@ -5,7 +5,7 @@
export {};
-const { findStyleByCssHref } = require("../../src/effect");
+const { findStyleByCssHref, dispatchStyleSheetLoadAsync } = require("../../src/effect");
const HREF = "https://cdn.example.com/assets/shared.css";
const CSS = ".box{width:100%;height:100%}";
@@ -34,3 +34,42 @@ describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", (
expect(findStyleByCssHref(document, "https://cdn.example.com/assets/other.css")).toBeNull();
});
});
+
+describe("命中去重后的 load 派发 / 消费方监听注册晚于 appendChild", () => {
+ function makeLink(): HTMLLinkElement {
+ const link = document.createElement("link");
+ link.setAttribute("rel", "stylesheet");
+ link.setAttribute("href", HREF);
+ return link;
+ }
+
+ it("监听在派发之后才注册时仍能收到 load(Vite preload 的顺序)", async () => {
+ const link = makeLink();
+ let loaded = 0;
+
+ // 对应运行时:劫持的 appendChild 内部命中去重后补发 load
+ dispatchStyleSheetLoadAsync(link);
+ // Vite preload 是在 appendChild 返回之后才 addEventListener("load")
+ const loadPromise = new Promise((resolve) => {
+ link.addEventListener("load", () => {
+ loaded += 1;
+ resolve();
+ });
+ });
+
+ await expect(loadPromise).resolves.toBeUndefined();
+ expect(loaded).toBe(1);
+ });
+
+ it("不在调用栈内同步派发", async () => {
+ const link = makeLink();
+ const onLoad = jest.fn();
+ link.addEventListener("load", onLoad);
+
+ dispatchStyleSheetLoadAsync(link);
+ expect(onLoad).not.toHaveBeenCalled();
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(onLoad).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts
index d64f63e3e..837caa8bc 100644
--- a/packages/wujie-core/src/effect.ts
+++ b/packages/wujie-core/src/effect.ts
@@ -285,6 +285,16 @@ export function findStyleByCssHref(doc: Document | null, href: string): HTMLStyl
return null;
}
+/**
+ * 命中去重后对原 link 补发 load,让等待 stylesheet 的消费方(如 Vite preload)继续执行。
+ *
+ * 必须异步派发:消费方是在 appendChild 返回之后才 addEventListener("load"),
+ * 而本函数由劫持的 appendChild 同步调用,在调用栈内同步派发时监听尚未注册,事件会被丢弃。
+ */
+export function dispatchStyleSheetLoadAsync(linkElement: HTMLLinkElement): void {
+ setTimeout(() => manualInvokeElementEvent(linkElement, "load"), 0);
+}
+
let dynamicScriptExecStack = Promise.resolve();
function rewriteAppendOrInsertChild(opts: {
rawDOMAppendOrInsertBefore: (newChild: T, refChild?: Node | null) => T;
@@ -333,9 +343,10 @@ function rewriteAppendOrInsertChild(opts: {
if (!styleHref || exclude) return;
// 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。
- // 仍派发 load,避免 Vite preload 一直等待 stylesheet 的 load 事件。
+ // 仍需对原 link 派发 load,避免 Vite preload 一直等待 stylesheet 的 load 事件;
+ // 派发时机见 dispatchStyleSheetLoadAsync。
if (findStyleByCssHref(iframeDocument, styleHref)) {
- manualInvokeElementEvent(linkElement, "load");
+ dispatchStyleSheetLoadAsync(linkElement);
return;
}
From 5894407a52f5b272cc466db38dff9d4de13d2986 Mon Sep 17 00:00:00 2001
From: KeyToLove <370621755@qq.com>
Date: Fri, 13 Nov 2026 11:18:32 +0800
Subject: [PATCH 3/5] fix(wujie-core): harden stylesheet href dedupe lookup
Normalize hrefs before comparing so query encodings still match, escape
the embed attribute, and dispatch error when a failed entry style is empty.
---
.../__test__/unit/css-href-dedupe.test.ts | 36 ++++++++++++++-
packages/wujie-core/src/effect.ts | 46 +++++++++++++------
packages/wujie-core/src/entry.ts | 17 ++++++-
3 files changed, 82 insertions(+), 17 deletions(-)
diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
index 1b378de2c..216b43a41 100644
--- a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
+++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
@@ -5,7 +5,7 @@
export {};
-const { findStyleByCssHref, dispatchStyleSheetLoadAsync } = require("../../src/effect");
+const { findStyleByCssHref, dispatchStyleSheetLoadAsync, canonicalCssHref } = require("../../src/effect");
const HREF = "https://cdn.example.com/assets/shared.css";
const CSS = ".box{width:100%;height:100%}";
@@ -33,6 +33,26 @@ describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", (
document.head.innerHTML = ``;
expect(findStyleByCssHref(document, "https://cdn.example.com/assets/other.css")).toBeNull();
});
+
+ it("属性值经过 HTML 转义后仍能按原 href 命中", () => {
+ const href = 'https://cdn.example.com/assets/shared.css?q="a"&b=1';
+ const style = document.createElement("style");
+ style.setAttribute("data-wujie-css-href", canonicalCssHref(href));
+ style.textContent = `/* ${href} */${CSS}`;
+ document.head.appendChild(style);
+ document.head.innerHTML = document.head.innerHTML;
+
+ const found = findStyleByCssHref(document, href);
+ expect(found).not.toBeNull();
+ expect(found.getAttribute("data-wujie-css-href")).toBe(canonicalCssHref(href));
+ });
+
+ it("查询串编码不同的同一绝对地址仍能命中", () => {
+ const stored = "https://cdn.example.com/assets/shared.css?v=a%20b";
+ const lookup = "https://cdn.example.com/assets/shared.css?v=a b";
+ document.head.innerHTML = ``;
+ expect(findStyleByCssHref(document, lookup)).not.toBeNull();
+ });
});
describe("命中去重后的 load 派发 / 消费方监听注册晚于 appendChild", () => {
@@ -72,4 +92,18 @@ describe("命中去重后的 load 派发 / 消费方监听注册晚于 appendChi
await new Promise((resolve) => setTimeout(resolve, 0));
expect(onLoad).toHaveBeenCalledTimes(1);
});
+
+ it("显式 error 时不派发 load", async () => {
+ const link = makeLink();
+ const onLoad = jest.fn();
+ const onError = jest.fn();
+ link.addEventListener("load", onLoad);
+ link.addEventListener("error", onError);
+
+ dispatchStyleSheetLoadAsync(link, "error");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(onLoad).not.toHaveBeenCalled();
+ expect(onError).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts
index 837caa8bc..1f8032da4 100644
--- a/packages/wujie-core/src/effect.ts
+++ b/packages/wujie-core/src/effect.ts
@@ -264,35 +264,47 @@ export function deferStyleSheetByHref(opts: {
}, DEFER_STYLE_HREF_TIMEOUT);
}
-function cssHrefLookupValue(href: string): string {
- return String(href).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+/**
+ * 去重键用 URL 序列化后的绝对地址。
+ * 入口模板走 URL#toString,动态插入走 URL#href;两者在查询串空格等字符上可能不一致,比较前先归一。
+ */
+export function canonicalCssHref(href: string): string {
+ if (!href) return "";
+ try {
+ return new URL(href).href;
+ } catch {
+ return href;
+ }
}
/**
* 按绝对 href 查找已转换的样式。
* 优先匹配动态占位和入口 HTML 写入的 data-wujie-css-href;
* 没有该属性时,兼容旧的注释形态:style 文本以 `/* href *\/` 开头。
+ * 不用属性选择器:href 里的引号会截断选择器,入口 HTML 又必须先做属性转义。
*/
export function findStyleByCssHref(doc: Document | null, href: string): HTMLStyleElement | null {
if (!href || !doc) return null;
- const marked = doc.querySelector(`style[data-wujie-css-href="${cssHrefLookupValue(href)}"]`);
- if (marked) return marked as HTMLStyleElement;
+ const target = canonicalCssHref(href);
const styles = doc.querySelectorAll("style");
for (let i = 0; i < styles.length; i++) {
- const text = styles[i].textContent || "";
- if (text.indexOf(`/* ${href} */`) === 0) return styles[i] as HTMLStyleElement;
+ const style = styles[i] as HTMLStyleElement;
+ const marked = style.getAttribute("data-wujie-css-href");
+ if (marked && canonicalCssHref(marked) === target) return style;
+ if (!marked && (style.textContent || "").indexOf(`/* ${href} */`) === 0) return style;
}
return null;
}
/**
- * 命中去重后对原 link 补发 load,让等待 stylesheet 的消费方(如 Vite preload)继续执行。
+ * 命中去重后对原 link 补发 load 或 error。
+ * 入口 CSS 请求失败时仍会留下带 href、内容为空的 style,此时应派发 error,避免 Vite preload 把没加载到的 CSS 当成成功。
*
- * 必须异步派发:消费方是在 appendChild 返回之后才 addEventListener("load"),
+ * 必须异步派发:消费方是在 appendChild 返回之后才 addEventListener,
* 而本函数由劫持的 appendChild 同步调用,在调用栈内同步派发时监听尚未注册,事件会被丢弃。
*/
-export function dispatchStyleSheetLoadAsync(linkElement: HTMLLinkElement): void {
- setTimeout(() => manualInvokeElementEvent(linkElement, "load"), 0);
+export function dispatchStyleSheetLoadAsync(linkElement: HTMLLinkElement, event: "load" | "error" = "load"): void {
+ setTimeout(() => manualInvokeElementEvent(linkElement, event), 0);
}
let dynamicScriptExecStack = Promise.resolve();
@@ -343,10 +355,13 @@ function rewriteAppendOrInsertChild(opts: {
if (!styleHref || exclude) return;
// 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。
- // 仍需对原 link 派发 load,避免 Vite preload 一直等待 stylesheet 的 load 事件;
- // 派发时机见 dispatchStyleSheetLoadAsync。
- if (findStyleByCssHref(iframeDocument, styleHref)) {
- dispatchStyleSheetLoadAsync(linkElement);
+ // 仍需对原 link 派发事件,避免 Vite preload 一直等待。
+ // 占位 style 在 fetch 完成前也没有内容,不能据此判失败;只有入口请求失败留下的空 style 才派发 error。
+ const existingStyle = findStyleByCssHref(iframeDocument, styleHref);
+ if (existingStyle) {
+ const awaitingContent = existingStyle.hasAttribute("data-wujie-css-pending");
+ const failed = !awaitingContent && !existingStyle.textContent;
+ dispatchStyleSheetLoadAsync(linkElement, failed ? "error" : "load");
return;
}
@@ -355,6 +370,7 @@ function rewriteAppendOrInsertChild(opts: {
const placeholderElement = iframeDocument.createElement("style");
setAttrsToElement(placeholderElement, rawAttrs);
placeholderElement.setAttribute("data-wujie-css-href", styleHref);
+ placeholderElement.setAttribute("data-wujie-css-pending", "");
rawDOMAppendOrInsertBefore.call(this, placeholderElement, refChild);
getExternalStyleSheets(
@@ -375,6 +391,7 @@ function rewriteAppendOrInsertChild(opts: {
const cssLoader = getCssLoader({ plugins, replace });
placeholderElement.innerHTML = cssLoader(content, src, curUrl);
if (src) placeholderElement.setAttribute("data-wujie-css-href", src);
+ placeholderElement.removeAttribute("data-wujie-css-pending");
styleSheetElements.push(placeholderElement);
// 处理样式补丁
handleStylesheetElementPatch(placeholderElement, sandbox);
@@ -383,6 +400,7 @@ function rewriteAppendOrInsertChild(opts: {
if (element === linkElement) element = null;
},
() => {
+ placeholderElement.removeAttribute("data-wujie-css-pending");
manualInvokeElementEvent(linkElement, "error");
if (element === linkElement) element = null;
}
diff --git a/packages/wujie-core/src/entry.ts b/packages/wujie-core/src/entry.ts
index e75e82fde..c3f4aa7f9 100644
--- a/packages/wujie-core/src/entry.ts
+++ b/packages/wujie-core/src/entry.ts
@@ -5,7 +5,15 @@ import processTpl, {
ScriptBaseObject,
StyleObject,
} from "./template";
-import { defaultGetPublicPath, getInlineCode, requestIdleCallback, error, compose, getCurUrl } from "./utils";
+import {
+ defaultGetPublicPath,
+ getInlineCode,
+ requestIdleCallback,
+ error,
+ compose,
+ getCurUrl,
+ getAbsolutePath,
+} from "./utils";
import {
WUJIE_TIPS_NO_FETCH,
WUJIE_TIPS_SCRIPT_ERROR_REQUESTED,
@@ -104,11 +112,12 @@ async function getEmbedHTML(template, styleResultList: StyleResultList): Promise
styleResultList.map((styleResult, index) =>
styleResult.contentPromise.then((content) => {
if (styleResult.src) {
+ const hrefAttr = escapeHtmlAttr(getAbsolutePath(styleResult.src, styleResult.src));
embedHTML = embedHTML.replace(
genLinkReplaceSymbol(styleResult.src),
styleResult.ignore
? ``
- : ``
+ : ``
);
} else if (content) {
embedHTML = embedHTML.replace(
@@ -123,6 +132,10 @@ async function getEmbedHTML(template, styleResultList: StyleResultList): Promise
const isInlineCode = (code) => code.startsWith("<");
+function escapeHtmlAttr(value: string): string {
+ return String(value).replace(/&/g, "&").replace(/"/g, """);
+}
+
const fetchAssets = (
src: string,
cache: Object,
From a50307a1b5c659692b98e839045126a1b1d74d55 Mon Sep 17 00:00:00 2001
From: KeyToLove <370621755@qq.com>
Date: Fri, 13 Nov 2026 17:54:14 +0800
Subject: [PATCH 4/5] fix(wujie-core): wait for pending stylesheet before
dispatching load
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.
---
.../__test__/unit/css-href-dedupe.test.ts | 117 ++++++++++++++++++
packages/wujie-core/src/effect.ts | 36 +++++-
packages/wujie-core/src/entry.ts | 4 +-
3 files changed, 152 insertions(+), 5 deletions(-)
diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
index 216b43a41..dfa4d79f2 100644
--- a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
+++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
@@ -107,3 +107,120 @@ describe("命中去重后的 load 派发 / 消费方监听注册晚于 appendChi
expect(onError).toHaveBeenCalledTimes(1);
});
});
+
+describe("appendChild 劫持 / 同 href 去重的派发时机", () => {
+ const { patchRenderEffect } = require("../../src/effect");
+ const { addSandboxCacheWithWujie, deleteWujieById } = require("../../src/common");
+ const { clearAssetsCache } = require("../../src/entry");
+
+ const WUJIE_ID = "css-href-dedupe-app";
+ const HREF = "https://cdn.example.com/assets/shared.css";
+ let fetchGate: { resolve: (value: string) => void; reject: (reason?: unknown) => void };
+ let sandbox: any;
+
+ function makeLink(): HTMLLinkElement {
+ const link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.href = HREF;
+ return link;
+ }
+
+ function eventOf(link: HTMLLinkElement, type: "load" | "error"): Promise {
+ return new Promise((resolve) => link.addEventListener(type, () => resolve()));
+ }
+
+ beforeEach(() => {
+ document.head.innerHTML = "";
+ document.body.innerHTML = "";
+ clearAssetsCache();
+ let resolveFetch: (value: string) => void;
+ let rejectFetch: (reason?: unknown) => void;
+ const pending = new Promise((resolve, reject) => {
+ resolveFetch = resolve;
+ rejectFetch = reject;
+ });
+ fetchGate = { resolve: resolveFetch, reject: rejectFetch };
+ sandbox = {
+ id: WUJIE_ID,
+ styleSheetElements: [],
+ replace: null,
+ plugins: [],
+ lifecycles: {},
+ proxyLocation: { protocol: "https:", host: "cdn.example.com", pathname: "/", href: "https://cdn.example.com/" },
+ fiber: false,
+ degrade: true,
+ iframe: { contentDocument: document, contentWindow: window },
+ fetch: jest.fn(() => pending.then((text) => ({ status: 200, text: () => Promise.resolve(text) }))),
+ };
+ addSandboxCacheWithWujie(WUJIE_ID, sandbox);
+ patchRenderEffect(document, WUJIE_ID, true);
+ });
+
+ afterEach(() => {
+ deleteWujieById(WUJIE_ID);
+ clearAssetsCache();
+ });
+
+ it("占位还在拉取时,第二份 link 要等原来的请求结束才收到 load", async () => {
+ const first = makeLink();
+ const second = makeLink();
+ const firstLoad = eventOf(first, "load");
+ const secondLoad = eventOf(second, "load");
+ let secondLoaded = false;
+ second.addEventListener("load", () => {
+ secondLoaded = true;
+ });
+
+ document.head.appendChild(first);
+ document.head.appendChild(second);
+ await Promise.resolve();
+
+ expect(document.head.querySelectorAll("style")).toHaveLength(1);
+ expect(document.head.querySelector("style").hasAttribute("data-wujie-css-pending")).toBe(true);
+ expect(secondLoaded).toBe(false);
+
+ fetchGate.resolve(".box{width:100%}");
+ await firstLoad;
+ await secondLoad;
+ expect(document.head.querySelector("style").getAttribute("data-wujie-css-state")).toBe("loaded");
+ expect(document.head.querySelector("style").textContent).toContain(".box{width:100%}");
+ });
+
+ it("请求成功但内容为空时,后来的 link 收到 load 而不是 error", async () => {
+ const first = makeLink();
+ document.head.appendChild(first);
+ fetchGate.resolve("");
+ await eventOf(first, "load");
+
+ const style = document.head.querySelector("style");
+ expect(style.textContent).toBe("");
+ expect(style.getAttribute("data-wujie-css-state")).toBe("loaded");
+
+ const second = makeLink();
+ const secondLoad = eventOf(second, "load");
+ const onError = jest.fn();
+ second.addEventListener("error", onError);
+ document.head.appendChild(second);
+ await secondLoad;
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(document.head.querySelectorAll("style")).toHaveLength(1);
+ });
+
+ it("入口失败留下的空 style 让后来的 link 收到 error", async () => {
+ const failed = document.createElement("style");
+ failed.setAttribute("data-wujie-css-href", HREF);
+ failed.setAttribute("data-wujie-css-state", "error");
+ document.head.appendChild(failed);
+
+ const link = makeLink();
+ const onError = eventOf(link, "error");
+ const onLoad = jest.fn();
+ link.addEventListener("load", onLoad);
+ document.head.appendChild(link);
+ await onError;
+
+ expect(onLoad).not.toHaveBeenCalled();
+ expect(document.head.querySelectorAll("style")).toHaveLength(1);
+ });
+});
diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts
index 1f8032da4..62d40dc1b 100644
--- a/packages/wujie-core/src/effect.ts
+++ b/packages/wujie-core/src/effect.ts
@@ -307,6 +307,26 @@ export function dispatchStyleSheetLoadAsync(linkElement: HTMLLinkElement, event:
setTimeout(() => manualInvokeElementEvent(linkElement, event), 0);
}
+type StyleSheetWaiter = {
+ linkElement: HTMLLinkElement;
+};
+
+/**
+ * 同一 href 还在拉取时,后来的 link 不能立刻收到 load。
+ * 登记到占位 style 上,等原来那次请求结束再派发同一个结果。
+ */
+function enqueueStyleSheetWaiter(styleElement: HTMLStyleElement, linkElement: HTMLLinkElement): void {
+ const waiters = ((styleElement as any)._wujieStyleWaiters || []) as StyleSheetWaiter[];
+ waiters.push({ linkElement });
+ (styleElement as any)._wujieStyleWaiters = waiters;
+}
+
+function flushStyleSheetWaiters(styleElement: HTMLStyleElement, event: "load" | "error"): void {
+ const waiters = ((styleElement as any)._wujieStyleWaiters || []) as StyleSheetWaiter[];
+ (styleElement as any)._wujieStyleWaiters = [];
+ waiters.forEach(({ linkElement }) => dispatchStyleSheetLoadAsync(linkElement, event));
+}
+
let dynamicScriptExecStack = Promise.resolve();
function rewriteAppendOrInsertChild(opts: {
rawDOMAppendOrInsertBefore: (newChild: T, refChild?: Node | null) => T;
@@ -356,11 +376,14 @@ function rewriteAppendOrInsertChild(opts: {
// 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。
// 仍需对原 link 派发事件,避免 Vite preload 一直等待。
- // 占位 style 在 fetch 完成前也没有内容,不能据此判失败;只有入口请求失败留下的空 style 才派发 error。
+ // pending 表示原来那次请求还没结束,此时不能派发 load,否则 preload 后面的 chunk 会提前执行。
const existingStyle = findStyleByCssHref(iframeDocument, styleHref);
if (existingStyle) {
- const awaitingContent = existingStyle.hasAttribute("data-wujie-css-pending");
- const failed = !awaitingContent && !existingStyle.textContent;
+ if (existingStyle.hasAttribute("data-wujie-css-pending")) {
+ enqueueStyleSheetWaiter(existingStyle, linkElement);
+ return;
+ }
+ const failed = existingStyle.getAttribute("data-wujie-css-state") === "error";
dispatchStyleSheetLoadAsync(linkElement, failed ? "error" : "load");
return;
}
@@ -382,7 +405,8 @@ function rewriteAppendOrInsertChild(opts: {
(content) => {
if (ignore && src) {
// 忽略的元素应该直接把对应元素插入,而不是用新的 link 标签进行替代插入,保证 element 的上下文正常
- // 移除占位元素,插入原始 link
+ // 移除占位元素,插入原始 link。排队的 link 不再有占位可等,按这条路径的成功语义补发 load。
+ flushStyleSheetWaiters(placeholderElement, "load");
placeholderElement.parentNode?.removeChild(placeholderElement);
rawDOMAppendOrInsertBefore.call(this, linkElement, refChild);
} else {
@@ -392,16 +416,20 @@ function rewriteAppendOrInsertChild(opts: {
placeholderElement.innerHTML = cssLoader(content, src, curUrl);
if (src) placeholderElement.setAttribute("data-wujie-css-href", src);
placeholderElement.removeAttribute("data-wujie-css-pending");
+ placeholderElement.setAttribute("data-wujie-css-state", "loaded");
styleSheetElements.push(placeholderElement);
// 处理样式补丁
handleStylesheetElementPatch(placeholderElement, sandbox);
manualInvokeElementEvent(linkElement, "load");
+ flushStyleSheetWaiters(placeholderElement, "load");
}
if (element === linkElement) element = null;
},
() => {
placeholderElement.removeAttribute("data-wujie-css-pending");
+ placeholderElement.setAttribute("data-wujie-css-state", "error");
manualInvokeElementEvent(linkElement, "error");
+ flushStyleSheetWaiters(placeholderElement, "error");
if (element === linkElement) element = null;
}
)
diff --git a/packages/wujie-core/src/entry.ts b/packages/wujie-core/src/entry.ts
index c3f4aa7f9..de28c2c64 100644
--- a/packages/wujie-core/src/entry.ts
+++ b/packages/wujie-core/src/entry.ts
@@ -113,11 +113,13 @@ async function getEmbedHTML(template, styleResultList: StyleResultList): Promise
styleResult.contentPromise.then((content) => {
if (styleResult.src) {
const hrefAttr = escapeHtmlAttr(getAbsolutePath(styleResult.src, styleResult.src));
+ const failed = !content;
+ const stateAttr = failed ? ' data-wujie-css-state="error"' : "";
embedHTML = embedHTML.replace(
genLinkReplaceSymbol(styleResult.src),
styleResult.ignore
? ``
- : ``
+ : ``
);
} else if (content) {
embedHTML = embedHTML.replace(
From f05e5a301b7fad917da48002946ca97182f3ee55 Mon Sep 17 00:00:00 2001
From: yiludege
Date: Sat, 14 Nov 2026 11:22:16 +0800
Subject: [PATCH 5/5] =?UTF-8?q?fix(wujie-core):=20=E5=B7=B2=E6=9C=89?=
=?UTF-8?q?=E6=A0=B7=E5=BC=8F=E4=B8=BA=E7=A9=BA=E6=97=B6=E4=B8=8D=E5=A4=8D?=
=?UTF-8?q?=E7=94=A8=EF=BC=8C=E6=8C=89=E5=8E=9F=E6=B5=81=E7=A8=8B=E9=87=8D?=
=?UTF-8?q?=E6=96=B0=E8=AF=B7=E6=B1=82?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
样式请求失败时 fetchAssets 也返回空串,空文件与请求失败无法区分。
原先入口为空的 style 会被标成 error,后来的动态 link 命中后收到 error,
Vite preload 随之报错,动态 import 的 chunk 不再执行。
- 命中有内容的样式才去重并补发 load;pending 时排队等待原请求结果
- 已有样式都为空时不复用,按原流程重新请求并打印 warn,请求失败的情况可以恢复
- 去掉 data-wujie-css-state 及入口的 failed 判断
Co-authored-by: Cursor
---
.../__test__/unit/css-href-dedupe.test.ts | 129 ++++++++++++------
packages/wujie-core/src/constant.ts | 1 +
packages/wujie-core/src/effect.ts | 47 ++++---
packages/wujie-core/src/entry.ts | 4 +-
4 files changed, 121 insertions(+), 60 deletions(-)
diff --git a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
index dfa4d79f2..d2bd90373 100644
--- a/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
+++ b/packages/wujie-core/__test__/unit/css-href-dedupe.test.ts
@@ -5,33 +5,43 @@
export {};
-const { findStyleByCssHref, dispatchStyleSheetLoadAsync, canonicalCssHref } = require("../../src/effect");
+const {
+ findStylesByCssHref,
+ hasStyleSheetContent,
+ dispatchStyleSheetLoadAsync,
+ canonicalCssHref,
+} = require("../../src/effect");
const HREF = "https://cdn.example.com/assets/shared.css";
const CSS = ".box{width:100%;height:100%}";
-describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", () => {
+describe("findStylesByCssHref / 入口 HTML 与动态 preload 同 href 去重", () => {
afterEach(() => {
document.head.innerHTML = "";
});
it("能匹配带 data-wujie-css-href 的入口 style", () => {
document.head.innerHTML = ``;
- const found = findStyleByCssHref(document, HREF);
- expect(found).not.toBeNull();
+ const [found] = findStylesByCssHref(document, HREF);
+ expect(found).toBeDefined();
expect(found.getAttribute("data-wujie-css-href")).toBe(HREF);
});
it("没有属性时能匹配注释开头的旧入口 style", () => {
document.head.innerHTML = ``;
- const found = findStyleByCssHref(document, HREF);
- expect(found).not.toBeNull();
+ const [found] = findStylesByCssHref(document, HREF);
+ expect(found).toBeDefined();
expect(found.textContent.indexOf(`/* ${HREF} */`)).toBe(0);
});
it("不同 href 不应命中", () => {
document.head.innerHTML = ``;
- expect(findStyleByCssHref(document, "https://cdn.example.com/assets/other.css")).toBeNull();
+ expect(findStylesByCssHref(document, "https://cdn.example.com/assets/other.css")).toHaveLength(0);
+ });
+
+ it("返回同 href 的全部 style", () => {
+ document.head.innerHTML = ``;
+ expect(findStylesByCssHref(document, HREF)).toHaveLength(2);
});
it("属性值经过 HTML 转义后仍能按原 href 命中", () => {
@@ -42,8 +52,8 @@ describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", (
document.head.appendChild(style);
document.head.innerHTML = document.head.innerHTML;
- const found = findStyleByCssHref(document, href);
- expect(found).not.toBeNull();
+ const [found] = findStylesByCssHref(document, href);
+ expect(found).toBeDefined();
expect(found.getAttribute("data-wujie-css-href")).toBe(canonicalCssHref(href));
});
@@ -51,7 +61,26 @@ describe("findStyleByCssHref / 入口 HTML 与动态 preload 同 href 去重", (
const stored = "https://cdn.example.com/assets/shared.css?v=a%20b";
const lookup = "https://cdn.example.com/assets/shared.css?v=a b";
document.head.innerHTML = ``;
- expect(findStyleByCssHref(document, lookup)).not.toBeNull();
+ expect(findStylesByCssHref(document, lookup)).toHaveLength(1);
+ });
+});
+
+describe("hasStyleSheetContent / 是否可复用", () => {
+ function styleOf(text: string): HTMLStyleElement {
+ const style = document.createElement("style");
+ style.textContent = text;
+ return style;
+ }
+
+ it("有规则的样式可复用", () => {
+ expect(hasStyleSheetContent(styleOf(`/* ${HREF} */${CSS}`))).toBe(true);
+ expect(hasStyleSheetContent(styleOf(CSS))).toBe(true);
+ });
+
+ it("只有入口注释或为空的样式不可复用", () => {
+ expect(hasStyleSheetContent(styleOf(`/* ${HREF} */`))).toBe(false);
+ expect(hasStyleSheetContent(styleOf(""))).toBe(false);
+ expect(hasStyleSheetContent(styleOf(" \n "))).toBe(false);
});
});
@@ -182,45 +211,69 @@ describe("appendChild 劫持 / 同 href 去重的派发时机", () => {
fetchGate.resolve(".box{width:100%}");
await firstLoad;
await secondLoad;
- expect(document.head.querySelector("style").getAttribute("data-wujie-css-state")).toBe("loaded");
+ expect(document.head.querySelector("style").hasAttribute("data-wujie-css-pending")).toBe(false);
expect(document.head.querySelector("style").textContent).toContain(".box{width:100%}");
});
- it("请求成功但内容为空时,后来的 link 收到 load 而不是 error", async () => {
- const first = makeLink();
- document.head.appendChild(first);
- fetchGate.resolve("");
- await eventOf(first, "load");
-
- const style = document.head.querySelector("style");
- expect(style.textContent).toBe("");
- expect(style.getAttribute("data-wujie-css-state")).toBe("loaded");
+ it("入口已有内容时直接复用,不再请求", async () => {
+ document.head.innerHTML = ``;
- const second = makeLink();
- const secondLoad = eventOf(second, "load");
+ const link = makeLink();
const onError = jest.fn();
- second.addEventListener("error", onError);
- document.head.appendChild(second);
- await secondLoad;
+ link.addEventListener("error", onError);
+ document.head.appendChild(link);
+ await eventOf(link, "load");
expect(onError).not.toHaveBeenCalled();
+ expect(sandbox.fetch).not.toHaveBeenCalled();
expect(document.head.querySelectorAll("style")).toHaveLength(1);
});
- it("入口失败留下的空 style 让后来的 link 收到 error", async () => {
- const failed = document.createElement("style");
- failed.setAttribute("data-wujie-css-href", HREF);
- failed.setAttribute("data-wujie-css-state", "error");
- document.head.appendChild(failed);
+ describe("已有样式为空时不复用", () => {
+ let warnSpy: jest.SpyInstance;
- const link = makeLink();
- const onError = eventOf(link, "error");
- const onLoad = jest.fn();
- link.addEventListener("load", onLoad);
- document.head.appendChild(link);
- await onError;
+ beforeEach(() => {
+ warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
+ });
- expect(onLoad).not.toHaveBeenCalled();
- expect(document.head.querySelectorAll("style")).toHaveLength(1);
+ afterEach(() => {
+ warnSpy.mockRestore();
+ });
+
+ it("入口请求失败留下的空 style:后来的 link 重新请求,成功后收到 load", async () => {
+ document.head.innerHTML = ``;
+
+ const link = makeLink();
+ const onError = jest.fn();
+ link.addEventListener("error", onError);
+ const linkLoad = eventOf(link, "load");
+ document.head.appendChild(link);
+ fetchGate.resolve(CSS);
+ await linkLoad;
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(sandbox.fetch).toHaveBeenCalledTimes(1);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("内容为空"), HREF);
+ const styles = document.head.querySelectorAll("style");
+ expect(styles).toHaveLength(2);
+ expect(styles[1].textContent).toContain(CSS);
+ });
+
+ it("空 CSS 文件:后来的 link 收到 load 而不是 error", async () => {
+ const first = makeLink();
+ document.head.appendChild(first);
+ fetchGate.resolve("");
+ await eventOf(first, "load");
+
+ const second = makeLink();
+ const secondLoad = eventOf(second, "load");
+ const onError = jest.fn();
+ second.addEventListener("error", onError);
+ document.head.appendChild(second);
+ await secondLoad;
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(document.head.querySelectorAll("style")).toHaveLength(2);
+ });
});
});
diff --git a/packages/wujie-core/src/constant.ts b/packages/wujie-core/src/constant.ts
index 8ea488986..13c09871f 100644
--- a/packages/wujie-core/src/constant.ts
+++ b/packages/wujie-core/src/constant.ts
@@ -41,6 +41,7 @@ export const WUJIE_TIPS_NO_FETCH = "window上不存在fetch属性,需要自行
export const WUJIE_TIPS_NOT_SUPPORTED = "当前浏览器不支持无界,子应用将采用iframe方式渲染";
export const WUJIE_TIPS_SCRIPT_ERROR_REQUESTED = "脚本请求出现错误";
export const WUJIE_TIPS_CSS_ERROR_REQUESTED = "样式请求出现错误";
+export const WUJIE_TIPS_CSS_DEDUPE_EMPTY = "已存在同地址样式但内容为空(空文件或此前请求失败),将重新请求";
export const WUJIE_TIPS_HTML_ERROR_REQUESTED = "html请求出现错误";
export const WUJIE_TIPS_REPEAT_RENDER = "无界组件短时间重复渲染了两次,可能存在性能问题请检查代码";
export const WUJIE_TIPS_NO_SCRIPT = "目标Script尚未准备好或已经被移除";
diff --git a/packages/wujie-core/src/effect.ts b/packages/wujie-core/src/effect.ts
index 62d40dc1b..c8ebd8715 100644
--- a/packages/wujie-core/src/effect.ts
+++ b/packages/wujie-core/src/effect.ts
@@ -33,6 +33,7 @@ import {
WUJIE_DATA_FLAG,
WUJIE_TIPS_REPEAT_RENDER,
WUJIE_TIPS_NO_SCRIPT,
+ WUJIE_TIPS_CSS_DEDUPE_EMPTY,
WUJIE_APP_ID,
} from "./constant";
import { ScriptObject, parseTagAttributes } from "./template";
@@ -278,27 +279,35 @@ export function canonicalCssHref(href: string): string {
}
/**
- * 按绝对 href 查找已转换的样式。
- * 优先匹配动态占位和入口 HTML 写入的 data-wujie-css-href;
+ * 按绝对 href 查找所有已转换的样式。
+ * 匹配动态占位和入口 HTML 写入的 data-wujie-css-href;
* 没有该属性时,兼容旧的注释形态:style 文本以 `/* href *\/` 开头。
* 不用属性选择器:href 里的引号会截断选择器,入口 HTML 又必须先做属性转义。
*/
-export function findStyleByCssHref(doc: Document | null, href: string): HTMLStyleElement | null {
- if (!href || !doc) return null;
+export function findStylesByCssHref(doc: Document | null, href: string): HTMLStyleElement[] {
+ if (!href || !doc) return [];
const target = canonicalCssHref(href);
const styles = doc.querySelectorAll("style");
+ const matched: HTMLStyleElement[] = [];
for (let i = 0; i < styles.length; i++) {
const style = styles[i] as HTMLStyleElement;
const marked = style.getAttribute("data-wujie-css-href");
- if (marked && canonicalCssHref(marked) === target) return style;
- if (!marked && (style.textContent || "").indexOf(`/* ${href} */`) === 0) return style;
+ if (marked && canonicalCssHref(marked) === target) matched.push(style);
+ else if (!marked && (style.textContent || "").indexOf(`/* ${href} */`) === 0) matched.push(style);
}
- return null;
+ return matched;
}
/**
- * 命中去重后对原 link 补发 load 或 error。
- * 入口 CSS 请求失败时仍会留下带 href、内容为空的 style,此时应派发 error,避免 Vite preload 把没加载到的 CSS 当成成功。
+ * 样式是否有可复用的内容(忽略入口 HTML 写入的开头注释 `/* href *\/`)。
+ * 样式请求失败时 fetchAssets 也返回空串,空文件与请求失败无法区分,两者都视为不可复用。
+ */
+export function hasStyleSheetContent(style: HTMLStyleElement): boolean {
+ return (style.textContent || "").replace(/^\s*\/\*[\s\S]*?\*\//, "").trim() !== "";
+}
+
+/**
+ * 命中去重后对原 link 补发事件。
*
* 必须异步派发:消费方是在 appendChild 返回之后才 addEventListener,
* 而本函数由劫持的 appendChild 同步调用,在调用栈内同步派发时监听尚未注册,事件会被丢弃。
@@ -377,16 +386,18 @@ function rewriteAppendOrInsertChild(opts: {
// 入口 HTML 已转成 style,或先前动态插入已占位时,不再插第二份。
// 仍需对原 link 派发事件,避免 Vite preload 一直等待。
// pending 表示原来那次请求还没结束,此时不能派发 load,否则 preload 后面的 chunk 会提前执行。
- const existingStyle = findStyleByCssHref(iframeDocument, styleHref);
- if (existingStyle) {
- if (existingStyle.hasAttribute("data-wujie-css-pending")) {
- enqueueStyleSheetWaiter(existingStyle, linkElement);
- return;
- }
- const failed = existingStyle.getAttribute("data-wujie-css-state") === "error";
- dispatchStyleSheetLoadAsync(linkElement, failed ? "error" : "load");
+ // 已有样式都为空时不复用,按原流程重新请求,请求失败的情况可以借此恢复。
+ const existingStyles = findStylesByCssHref(iframeDocument, styleHref);
+ if (existingStyles.some(hasStyleSheetContent)) {
+ dispatchStyleSheetLoadAsync(linkElement);
+ return;
+ }
+ const pendingStyle = existingStyles.find((style) => style.hasAttribute("data-wujie-css-pending"));
+ if (pendingStyle) {
+ enqueueStyleSheetWaiter(pendingStyle, linkElement);
return;
}
+ if (existingStyles.length) warn(WUJIE_TIPS_CSS_DEDUPE_EMPTY, styleHref);
// 立即创建占位 `
+ : ``
);
} else if (content) {
embedHTML = embedHTML.replace(