Skip to content

Commit 734431c

Browse files
domeniccodex
andcommitted
Align classic script and resource lifecycles
Replace the per-document resource loader, request manager, and generic resource queues with document-scoped cancellation and load-event delays. Fetch subresources through the dispatcher and let each element own its processing and events, instead of serializing unrelated images, stylesheets, and frames behind scripts. Implement the force-async flag and ordered dynamic scripts, capture inline source and the preparation-time document, and queue errors for empty or invalid script URLs. Suppress execution of prepared scripts whose node document no longer matches their preparation-time document, while allowing scripts moved back before execution. Ignore destructive external-script document.write() calls when there is no parser insertion point. Separate internal parsing completion from document.close(), which only finishes a script-created parser. Avoid replaying readiness and load events on repeated close calls. Deliver iframe load when its document finishes loading, including after document.open() during DOMContentLoaded, and suppress recursive iframe load events when reopening from an iframe load handler. Abort pending subresource and XHR requests in descendant documents when stopping a window, without firing resource completion events for canceled requests. Suppress pending parser completion events after abort. Give subsequent requests a fresh cancellation lifetime, and preserve already-fetched ordered dynamic scripts while releasing canceled scripts from the execution order. Use explicit abort listeners until the AbortSignal.any() issue at nodejs/node#65995 is fixed in supported Node.js versions. Wait for nested stylesheet imports, ignore import cycles, and fire one event for the owning element after imports finish. Both link and style fire load even when an import fails, matching Chromium and WebKit; top-level link fetch failures still fire error. Cover the import-event behavior with a tentative WPT because HTML's critical-subresource integration remains underspecified: whatwg/html#968. Restrict script-blocking stylesheet eligibility to parser-created elements, with link eligibility determined at creation. Cancel obsolete image and stylesheet requests so late responses cannot replace newer content. The parsers still cannot pause for external scripts, so parsing-blocking scripts remain chained in parser order. Incremental document.write(), fragment-script initialization, and full VM microtask checkpoints remain incomplete. Mark resource-timing tests that depend on parser blocking flaky, linking them to #2413, and distinguish independent upstream test races. Enable upstream dynamic-markup-insertion coverage, add lifecycle WPTs and script/resource benchmarks, and run tentative to-upstream WPTs while continuing to exclude upstream tentative tests. Co-authored-by: codex <[email protected]>
1 parent 7ce7eb8 commit 734431c

63 files changed

Lines changed: 2063 additions & 950 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎benchmark/dom/resources.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"use strict";
2+
const { Bench } = require("tinybench");
3+
const { JSDOM, requestInterceptor } = require("../..");
4+
5+
module.exports = () => {
6+
const bench = new Bench();
7+
for (const [name, markup] of [
8+
["20 inline style sheets", "<style>body { color: green }</style>".repeat(20)],
9+
["20 external style sheets", '<link rel="stylesheet" href="data:text/css,body{color:green}">'.repeat(20)],
10+
["10 child documents", '<iframe src="data:text/html,<p>hello</p>"></iframe>'.repeat(10)]
11+
]) {
12+
bench.add(`load ${name}`, async () => {
13+
const { window } = new JSDOM(markup, { resources: "usable" });
14+
await new Promise(resolve => {
15+
window.addEventListener("load", resolve);
16+
});
17+
window.close();
18+
});
19+
}
20+
21+
bench.add("close with 20 pending intercepted requests", async () => {
22+
const { window } = new JSDOM('<script async src="/pending.js"></script>'.repeat(20), {
23+
url: "https://example.test/", runScripts: "dangerously",
24+
resources: { interceptors: [requestInterceptor(() => new Promise(() => {}))] }
25+
});
26+
window.close();
27+
await new Promise(resolve => {
28+
setImmediate(resolve);
29+
});
30+
});
31+
32+
return bench;
33+
};

‎benchmark/dom/scripts.js‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"use strict";
2+
const { Bench } = require("tinybench");
3+
const { JSDOM } = require("../..");
4+
5+
module.exports = () => {
6+
const bench = new Bench();
7+
const { window } = new JSDOM("", { runScripts: "dangerously" });
8+
const { document } = window;
9+
window.scriptCount = 0;
10+
const source = "window.scriptCount++;";
11+
12+
bench.add("execute a dynamic inline script", () => {
13+
const script = document.createElement("script");
14+
script.text = source;
15+
document.body.appendChild(script);
16+
script.remove();
17+
});
18+
19+
bench.add("prepare an unsupported script type", () => {
20+
const script = document.createElement("script");
21+
script.type = "application/json";
22+
script.text = "{}";
23+
document.body.appendChild(script);
24+
script.remove();
25+
});
26+
27+
bench.add("parse and execute 100 inline scripts", () => {
28+
const dom = new JSDOM(`<script>${source}</script>`.repeat(100), {
29+
runScripts: "dangerously",
30+
beforeParse(scriptWindow) {
31+
scriptWindow.scriptCount = 0;
32+
}
33+
});
34+
dom.window.close();
35+
});
36+
37+
for (const attribute of ["", " async", " defer"]) {
38+
bench.add(`load 20 external scripts${attribute || " (blocking)"}`, async () => {
39+
const dom = new JSDOM(`<script${attribute} src="data:text/javascript,${source}"></script>`.repeat(20), {
40+
runScripts: "dangerously",
41+
resources: "usable",
42+
beforeParse(scriptWindow) {
43+
scriptWindow.scriptCount = 0;
44+
}
45+
});
46+
await new Promise(resolve => {
47+
dom.window.addEventListener("load", resolve);
48+
});
49+
dom.window.close();
50+
});
51+
}
52+
53+
return bench;
54+
};

‎lib/api.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,13 @@ class JSDOM {
4141
this[window] = createWindow(normalized.windowOptions);
4242

4343
const documentImpl = this[window]._document;
44+
const finishParsing = documentImpl._startParsing();
4445

4546
normalized.beforeParse(this[window]._globalProxy);
4647

4748
parseIntoDocument(html, documentImpl);
4849

49-
documentImpl.close();
50+
finishParsing();
5051
}
5152

5253
get window() {

‎lib/jsdom/browser/Window.js‎

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -121,27 +121,16 @@ exports.createWindow = options => {
121121
// Not sure why this is necessary... TODO figure it out.
122122
Object.defineProperty(idlUtils.implForWrapper(window), idlUtils.wrapperSymbol, { get: () => window._globalProxy });
123123

124-
// Fire or prepare to fire load and pageshow events.
125-
process.nextTick(() => {
124+
window.document.addEventListener("load", () => {
126125
const documentImpl = window._document;
126+
fireAnEvent("load", window, undefined, {}, true);
127127
if (documentImpl._isDestroyed) {
128128
return;
129129
}
130130

131-
if (window.document.readyState === "complete") {
132-
fireAnEvent("load", window, undefined, {}, true);
133-
} else {
134-
window.document.addEventListener("load", () => {
135-
fireAnEvent("load", window, undefined, {}, true);
136-
if (documentImpl._isDestroyed) {
137-
return;
138-
}
139-
140-
if (!documentImpl._pageShowingFlag) {
141-
documentImpl._pageShowingFlag = true;
142-
fireAPageTransitionEvent("pageshow", window, false);
143-
}
144-
});
131+
if (!documentImpl._pageShowingFlag) {
132+
documentImpl._pageShowingFlag = true;
133+
fireAPageTransitionEvent("pageshow", window, false);
145134
}
146135
});
147136

@@ -807,10 +796,11 @@ function installOwnProperties(window, { settings, documentOptions, commonForOrig
807796
};
808797

809798
window.stop = function () {
810-
const manager = window._document._requestManager;
811-
if (manager) {
812-
manager.close();
799+
const doc = window._document;
800+
for (const child of doc._childDocuments) {
801+
child._defaultView.stop();
813802
}
803+
doc._abort();
814804
};
815805

816806
window.close = function () {
@@ -840,7 +830,7 @@ function installOwnProperties(window, { settings, documentOptions, commonForOrig
840830
idlUtils.implForWrapper(window)._removeAllEventListeners();
841831

842832
doc._removeAllEventListeners();
843-
doc._requestManager.close();
833+
doc._abort();
844834

845835
stopAllTimers();
846836
WebSocketImpl.cleanUpWindow(window);

‎lib/jsdom/browser/parser/html.js‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,25 @@ class JSDOMParse5Adapter {
7676
}
7777

7878
const element = createElement(ownerDocument, localName, namespace, null, isValue, willExecuteScript);
79+
if (localName === "style" && namespace === HTML_NS) {
80+
element._isOnStackOfOpenElements = true;
81+
}
82+
if (localName === "style" && namespace === HTML_NS && !this._fragment) {
83+
element._parserDocument = this._documentImpl;
84+
}
7985
this.adoptAttributes(element, attrs);
86+
if (localName === "link" && namespace === HTML_NS && !this._fragment) {
87+
element._markAsParserInserted(this._documentImpl);
88+
}
8089

8190
if (willExecuteScript) {
8291
const queue = customElementReactionsStack.pop();
8392
invokeCEReactions(queue);
8493
ownerDocument._throwOnDynamicMarkupInsertionCounter--;
8594
}
8695

87-
if ("_parserInserted" in element) {
88-
element._parserInserted = true;
96+
if (localName === "script" && namespace === HTML_NS) {
97+
element._markAsParserInserted(this._documentImpl);
8998
}
9099

91100
return element;

‎lib/jsdom/browser/parser/xml.js‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,26 +109,35 @@ function createParser(rootNode, globalObject, saxesOptions) {
109109
const isValue = tagAttributes.is === undefined ? null : tagAttributes.is.value;
110110

111111
const elem = createElement(ownerDocument, tagLocal, tagNamespace, tagPrefix, isValue, true);
112+
if (tagLocal === "style" && tagNamespace === HTML_NS) {
113+
elem._isOnStackOfOpenElements = true;
114+
}
112115

113116
// We mark a script element as "parser-inserted", which prevents it from
114117
// being immediately executed.
115118
if (tagLocal === "script" && tagNamespace === HTML_NS) {
116-
elem._parserInserted = true;
119+
elem._markAsParserInserted(rootNode._ownerDocument);
120+
}
121+
if (tagLocal === "style" && tagNamespace === HTML_NS && !saxesOptions.fragment) {
122+
elem._parserDocument = rootNode._ownerDocument;
117123
}
118124

119125
for (const key of Object.keys(tagAttributes)) {
120126
const { prefix, local, uri, value } = tagAttributes[key];
121127
attributes.setAttributeValue(elem, local, value, prefix === "" ? null : prefix, uri === "" ? null : uri);
122128
}
129+
if (tagLocal === "link" && tagNamespace === HTML_NS && !saxesOptions.fragment) {
130+
elem._markAsParserInserted(rootNode._ownerDocument);
131+
}
123132

124133
appendChild(elem);
125134
openStack.push(elem);
126135
});
127136

128137
parser.on("closetag", () => {
129138
const elem = openStack.pop();
130-
// Prepare scripts after their contents have been parsed.
131-
if (elem.localName === "script" && elem.namespaceURI === HTML_NS) {
139+
// Prepare scripts and update style blocks after their contents have been parsed.
140+
if ((elem.localName === "script" || elem.localName === "style") && elem.namespaceURI === HTML_NS) {
132141
elem._poppedOffStackOfOpenElements();
133142
}
134143
});

‎lib/jsdom/browser/resources/async-resource-queue.js‎

Lines changed: 0 additions & 114 deletions
This file was deleted.

‎lib/jsdom/browser/resources/jsdom-dispatcher.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const { parseURL, serializeURL, serializeURLOrigin, serializePath } = require("w
66
const dataURLFromRecord = require("data-urls").fromURLRecord;
77
const { Dispatcher } = require("undici");
88
const { toBase64 } = require("@exodus/bytes/base64.js");
9+
const { wrapperForImpl } = require("../../../generated/idl/utils");
910
const { utf8Encode } = require("../../living/helpers/encoding");
1011
const { sendStreamResponse } = require("./stream-handler");
1112

@@ -732,7 +733,7 @@ class JSDOMDispatcher extends Dispatcher {
732733
* @param {string} opts.url - The URL to fetch
733734
* @param {object} [opts.headers] - Request headers (include Referer if needed)
734735
* @param {AbortSignal} [opts.signal] - Abort signal
735-
* @param {Element} [opts.element] - The element initiating the request (default: null)
736+
* @param {ElementImpl|null} [opts.element] - The element implementation initiating the request (default: null)
736737
* @returns {Promise<{status: number, headers: object, body: Uint8Array, url: string, ok: boolean}>}
737738
*/
738739
async function fetchCollected(dispatcher, { url, headers, signal, element = null }) {
@@ -747,7 +748,7 @@ async function fetchCollected(dispatcher, { url, headers, signal, element = null
747748
method: "GET",
748749
headers,
749750
signal,
750-
opaque: { element, url }
751+
opaque: { element: wrapperForImpl(element), url }
751752
});
752753

753754
const body = await response.body.bytes();

0 commit comments

Comments
 (0)