Unverified Commit cad19c28 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: only search <head> for existing chunk tags (#100175)

### What?

Turbopack's browser runtime now looks for existing chunk tags in
`<head>` only, and `turbopack-dev-server` puts its chunk scripts into
`<head>` as `<script async>` instead of at the end of `<body>`.

Follow-up to #100047, answering [this review
comment](https://github.com/vercel/next.js/pull/100047#discussion_r4267298397).

### Why?

#100047 removed the document-wide `querySelectorAll` from the chunk-tag
lookup, but the lookup still iterated every `<script>`/`<link>` in the
document, so its cost grew with the page content.

I checked where chunk tags actually land in Next.js (Chromium; hard
loads, App Router soft navigation, Pages Router, Suspense streaming,
`loading.tsx`, PPR in prod):
- The tags the runtime looks up are all in `<head>`.
- The tags in `<body>` are the bootstrap `<script>` (a runtime chunk,
never looked up), late `<link rel=preload>` tags for `next/dynamic`
chunks in streamed boundaries, and, under PPR, a second copy of the
`noModule` polyfills script.

`turbopack-dev-server` was the one producer that put chunk scripts into
`<body>`.

Synthetic Chromium microbenchmark of the compiled lookup helper, 80
lookups, ms (before → after):

| CPU | Body elements | Before | After |
|---|---|---|---|
| 1× | 800 | 3.5 | 2.6 |
| 1× | 8,000 | 8.1 | 2.5 |
| 1× | 32,000 | 23.3 | 2.5 |
| 4× | 800 | 14.4 | 10.8 |
| 4× | 8,000 | 33.9 | 10.5 |
| 4× | 32,000 | 108.1 | 10.9 |

### How?

- **Runtime** (`runtime-backend-dom.ts`): `findChunkScripts` /
`findChunkLinks` iterate `document.head.getElementsByTagName(...)`.
Matching is unchanged (exact URL, `?query` suffix, decoded variant,
`rel` filter). This applies to chunk loads, CSS reloads and dev HMR
unloads. Tags in `<body>` are deliberately ignored:
  - a chunk whose tag is only in `<body>` gets a new tag in `<head>`;
- HMR unload leaves `<body>` copies, such as streamed `rel=preload`
links, in place.
- **Dev server** (`html.rs`): the HTML is rendered by a small pure
function. Stylesheets come first, then the chunk scripts as `<script
async>`, all in `<head>`; the page body stays in `<body>`. The runtime
doesn't depend on chunk execution order. Entry code may now run before
`<body>` is parsed, so it has to wait for the DOM itself if it touches
it.
- **Tests**:
  - `dynamic-chunk-dedupe` gains:
- a streamed `next/dynamic` route that asserts each chunk is requested
once and no tags are duplicated;
- a Turbopack-only on-demand case, where inert copies of the chunk's
tags in `<body>` must be ignored (it fails on the old lookup);
- a Turbopack dev case where HMR unload removes only the `<head>` tags
(it also fails on the old lookup).
  - The Rust unit tests cover the new dev-server HTML.
- **Snapshots** for the files that inline the DOM runtime are
regenerated.

Verified locally:
- `dynamic-chunk-dedupe` in Turbopack start, dev and cache components,
plus webpack start, where the Turbopack-only cases are skipped;
- `chunk-load-failure`, and the CSS and dynamic HMR suites;
- `cargo test -p turbopack-dev-server` and the snapshot tests;
- a `turbopack-cli dev` smoke test with a dynamic import and CSS.

<!-- NEXT_JS_LLM -->


<!-- fleet 00169b97-050c-43e3-a74e-5c9141d0996e -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 74c6c1b6
'use client'
import styles from './on-demand-widget.module.css'
export default function OnDemandWidget() {
return (
<p id="on-demand-widget" className={styles.text}>
on-demand widget
</p>
)
}
'use client'
import { lazy, Suspense, useState } from 'react'
// Only requested once the button is clicked, so its chunks are not part of
// the server-rendered HTML.
const OnDemandWidget = lazy(() => import('./on-demand-widget'))
export function OnDemand() {
const [show, setShow] = useState(false)
return (
<>
<button id="load" onClick={() => setShow(true)}>
load
</button>
{show ? (
<Suspense fallback={<p id="on-demand-loading">loading</p>}>
<OnDemandWidget />
</Suspense>
) : null}
</>
)
}
import { OnDemand } from './on-demand'
export default function Page() {
return (
<main>
<OnDemand />
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { StreamedClient } from './streamed-client'
// Resolves after the shell has been sent, so its `next/dynamic` chunk is
// announced by `<link rel=preload>` tags streamed into `<body>`.
async function Late() {
await connection()
await new Promise((resolve) => setTimeout(resolve, 1000))
return <StreamedClient />
}
export default function Page() {
return (
<main>
<p id="shell">shell</p>
<Suspense fallback={<p id="streamed-loading">loading</p>}>
<Late />
</Suspense>
</main>
)
}
'use client'
import dynamic from 'next/dynamic'
const StreamedWidget = dynamic(() => import('./streamed-widget'))
export function StreamedClient() {
return <StreamedWidget />
}
'use client'
import styles from './streamed-widget.module.css'
export default function StreamedWidget() {
return (
<p id="streamed-widget" className={styles.text}>
streamed widget
</p>
)
}
...@@ -217,33 +217,7 @@ impl DevHtmlAssetContent { ...@@ -217,33 +217,7 @@ impl DevHtmlAssetContent {
impl DevHtmlAssetContent { impl DevHtmlAssetContent {
#[turbo_tasks::function] #[turbo_tasks::function]
fn content(&self) -> Result<Vc<AssetContent>> { fn content(&self) -> Result<Vc<AssetContent>> {
let mut scripts = Vec::new(); let html: RcStr = render_html(&self.chunk_paths, self.body.as_deref())?.into();
let mut stylesheets = Vec::new();
for relative_path in &*self.chunk_paths {
if relative_path.ends_with(".js") {
scripts.push(format!("<script src=\"{relative_path}\"></script>"));
} else if relative_path.ends_with(".css") {
stylesheets.push(format!(
"<link data-turbopack rel=\"stylesheet\" href=\"{relative_path}\">"
));
} else {
anyhow::bail!("chunk with unknown asset type: {}", relative_path)
}
}
let body = match &self.body {
Some(body) => body.as_str(),
None => "",
};
let html: RcStr = format!(
"<!DOCTYPE html>\n<html>\n<head>\n{}\n</head>\n<body>\n{}\n{}\n</body>\n</html>",
stylesheets.join("\n"),
body,
scripts.join("\n"),
)
.into();
Ok(AssetContent::file( Ok(AssetContent::file(
FileContent::Content(File::from(html).with_content_type(TEXT_HTML_UTF_8)).cell(), FileContent::Content(File::from(html).with_content_type(TEXT_HTML_UTF_8)).cell(),
...@@ -291,3 +265,80 @@ impl Version for DevHtmlAssetVersion { ...@@ -291,3 +265,80 @@ impl Version for DevHtmlAssetVersion {
Vc::cell(hash.into()) Vc::cell(hash.into())
} }
} }
/// Renders the HTML page that loads the given chunks.
///
/// All chunk tags go into `<head>`, where the runtime looks for the tags of
/// already loaded chunks. Scripts are `async`: the runtime does not depend on
/// the order in which chunks execute, but code in a chunk may run before
/// `<body>` has been parsed.
fn render_html(chunk_paths: &[RcStr], body: Option<&str>) -> Result<String> {
let mut scripts = Vec::new();
let mut stylesheets = Vec::new();
for relative_path in chunk_paths {
if relative_path.ends_with(".js") {
scripts.push(format!("<script async src=\"{relative_path}\"></script>"));
} else if relative_path.ends_with(".css") {
stylesheets.push(format!(
"<link data-turbopack rel=\"stylesheet\" href=\"{relative_path}\">"
));
} else {
anyhow::bail!("chunk with unknown asset type: {}", relative_path)
}
}
Ok(format!(
"<!DOCTYPE html>\n<html>\n<head>\n{}\n</head>\n<body>\n{}\n</body>\n</html>",
stylesheets
.into_iter()
.chain(scripts)
.collect::<Vec<_>>()
.join("\n"),
body.unwrap_or_default(),
))
}
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use super::render_html;
#[test]
fn chunk_tags_are_in_head() {
let html = render_html(
&[
rcstr!("runtime.js"),
rcstr!("a.css"),
rcstr!("main.js"),
rcstr!("b.css"),
],
Some("<div id=\"root\"></div>"),
)
.unwrap();
assert_eq!(
html,
"<!DOCTYPE html>\n<html>\n<head>\n<link data-turbopack rel=\"stylesheet\" \
href=\"a.css\">\n<link data-turbopack rel=\"stylesheet\" href=\"b.css\">\n<script \
async src=\"runtime.js\"></script>\n<script async \
src=\"main.js\"></script>\n</head>\n<body>\n<div id=\"root\"></div>\n</body>\n</html>"
);
}
#[test]
fn empty_body() {
let html = render_html(&[rcstr!("main.js")], None).unwrap();
assert_eq!(
html,
"<!DOCTYPE html>\n<html>\n<head>\n<script async \
src=\"main.js\"></script>\n</head>\n<body>\n\n</body>\n</html>"
);
}
#[test]
fn unknown_chunk_type() {
assert!(render_html(&[rcstr!("main.wasm")], None).is_err());
}
}
...@@ -29,7 +29,7 @@ let DEV_BACKEND: DevRuntimeBackend ...@@ -29,7 +29,7 @@ let DEV_BACKEND: DevRuntimeBackend
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)) { for (const script of findChunkScripts(baseChunkUrl)) {
script.remove() script.remove()
......
...@@ -39,17 +39,23 @@ function matchesChunkUrl( ...@@ -39,17 +39,23 @@ function matchesChunkUrl(
) )
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
// loaded again through a new tag in `<head>`, and unloading a chunk leaves its
// `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/** /**
* Returns all `<script>` elements in the document whose `src` refers to `url`. * Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ */
function findChunkScripts(url: string): HTMLScriptElement[] { function findChunkScripts(url: string): HTMLScriptElement[] {
const decodedUrl = decodeURI(url) const decodedUrl = decodeURI(url)
const scripts = document.getElementsByTagName('script') const scripts = document.head.getElementsByTagName('script')
const result: HTMLScriptElement[] = [] const result: HTMLScriptElement[] = []
for (let i = 0; i < scripts.length; i++) { for (let i = 0; i < scripts.length; i++) {
const script = scripts[i] const script = scripts[i]
...@@ -61,7 +67,7 @@ function findChunkScripts(url: string): HTMLScriptElement[] { ...@@ -61,7 +67,7 @@ function findChunkScripts(url: string): HTMLScriptElement[] {
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ */
...@@ -70,7 +76,7 @@ function findChunkLinks( ...@@ -70,7 +76,7 @@ function findChunkLinks(
stylesheetsOnly: boolean = false stylesheetsOnly: boolean = false
): HTMLLinkElement[] { ): HTMLLinkElement[] {
const decodedUrl = decodeURI(url) const decodedUrl = decodeURI(url)
const links = document.getElementsByTagName('link') const links = document.head.getElementsByTagName('link')
const result: HTMLLinkElement[] = [] const result: HTMLLinkElement[] = []
for (let i = 0; i < links.length; i++) { for (let i = 0; i < links.length; i++) {
const link = links[i] const link = links[i]
...@@ -86,7 +92,7 @@ function findChunkLinks( ...@@ -86,7 +92,7 @@ function findChunkLinks(
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ */
function findChunkStylesheets(url: string): HTMLLinkElement[] { function findChunkStylesheets(url: string): HTMLLinkElement[] {
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="ef69da0e-1e88-28eb-53b3-a456eef8bf15")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="bdf2a5bb-33ac-1b9f-2ecf-28033b73cc7f")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js", "output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -2293,15 +2293,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2293,15 +2293,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2312,12 +2318,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2312,12 +2318,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2328,7 +2334,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2328,7 +2334,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2560,7 +2566,7 @@ let DEV_BACKEND; ...@@ -2560,7 +2566,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
...@@ -2653,5 +2659,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2653,5 +2659,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=ef69da0e-1e88-28eb-53b3-a456eef8bf15 //# debugId=bdf2a5bb-33ac-1b9f-2ecf-28033b73cc7f
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map
\ No newline at end of file
...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2559,7 +2565,7 @@ let DEV_BACKEND; ...@@ -2559,7 +2565,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
......
...@@ -1775,15 +1775,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -1775,15 +1775,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
// loaded again through a new tag in `<head>`, and unloading a chunk leaves its
// `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/** /**
* Returns all `<script>` elements in the document whose `src` refers to `url`. * Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
var decodedUrl = decodeURI(url); var decodedUrl = decodeURI(url);
var scripts = document.getElementsByTagName('script'); var scripts = document.head.getElementsByTagName('script');
var result = []; var result = [];
for(var i = 0; i < scripts.length; i++){ for(var i = 0; i < scripts.length; i++){
var script = scripts[i]; var script = scripts[i];
...@@ -1794,13 +1800,13 @@ function getAssetSuffixFromScriptSrc() { ...@@ -1794,13 +1800,13 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url) { */ function findChunkLinks(url) {
var stylesheetsOnly = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; var stylesheetsOnly = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
var decodedUrl = decodeURI(url); var decodedUrl = decodeURI(url);
var links = document.getElementsByTagName('link'); var links = document.head.getElementsByTagName('link');
var result = []; var result = [];
for(var i = 0; i < links.length; i++){ for(var i = 0; i < links.length; i++){
var _link_getAttribute; var _link_getAttribute;
...@@ -1812,7 +1818,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -1812,7 +1818,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
......
...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2559,7 +2565,7 @@ let DEV_BACKEND; ...@@ -2559,7 +2565,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
......
...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2559,7 +2565,7 @@ let DEV_BACKEND; ...@@ -2559,7 +2565,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
......
...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2559,7 +2565,7 @@ let DEV_BACKEND; ...@@ -2559,7 +2565,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
......
...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2292,15 +2292,21 @@ function getAssetSuffixFromScriptSrc() {
*/ function matchesChunkUrl(value, url, decodedUrl) { */ function matchesChunkUrl(value, url, decodedUrl) {
return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?')); return value != null && (value === url || value.startsWith(url + '?') || value === decodedUrl || value.startsWith(decodedUrl + '?'));
} }
// These lookups iterate the tag collection and compare attribute values as // These lookups only search `<head>`: the runtime inserts its chunk tags there,
// plain strings. A document-wide `querySelectorAll` with attribute selectors // and chunk tags rendered into the HTML are expected there too. Tags in
// costs time proportional to the size of the whole DOM on every call, and // `<body>` are deliberately ignored, so that the cost of a lookup does not grow
// would need the URL to be CSS-escaped. // with the size of the page content. A chunk whose tag is only in `<body>` is
/** // loaded again through a new tag in `<head>`, and unloading a chunk leaves its
* Returns all `<script>` elements in the document whose `src` refers to `url`. // `<body>` tags in place.
//
// They iterate the tag collection and compare attribute values as plain
// strings. `querySelectorAll` with attribute selectors would need the URL to be
// CSS-escaped.
/**
* Returns all `<script>` elements in `<head>` whose `src` refers to `url`.
*/ function findChunkScripts(url) { */ function findChunkScripts(url) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const scripts = document.getElementsByTagName('script'); const scripts = document.head.getElementsByTagName('script');
const result = []; const result = [];
for(let i = 0; i < scripts.length; i++){ for(let i = 0; i < scripts.length; i++){
const script = scripts[i]; const script = scripts[i];
...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2311,12 +2317,12 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link>` elements in the document whose `href` refers to `url`. * Returns all `<link>` elements in `<head>` whose `href` refers to `url`.
* With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet` * With `stylesheetsOnly`, only links whose `rel` is exactly `stylesheet`
* (ASCII case-insensitive) are returned. * (ASCII case-insensitive) are returned.
*/ function findChunkLinks(url, stylesheetsOnly = false) { */ function findChunkLinks(url, stylesheetsOnly = false) {
const decodedUrl = decodeURI(url); const decodedUrl = decodeURI(url);
const links = document.getElementsByTagName('link'); const links = document.head.getElementsByTagName('link');
const result = []; const result = [];
for(let i = 0; i < links.length; i++){ for(let i = 0; i < links.length; i++){
const link = links[i]; const link = links[i];
...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -2327,7 +2333,7 @@ function getAssetSuffixFromScriptSrc() {
return result; return result;
} }
/** /**
* Returns all `<link rel=stylesheet>` elements in the document whose `href` * Returns all `<link rel=stylesheet>` elements in `<head>` whose `href`
* refers to `url`. * refers to `url`.
*/ function findChunkStylesheets(url) { */ function findChunkStylesheets(url) {
return findChunkLinks(url, true); return findChunkLinks(url, true);
...@@ -2559,7 +2565,7 @@ let DEV_BACKEND; ...@@ -2559,7 +2565,7 @@ let DEV_BACKEND;
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS // Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated. // runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep // However, we still want to remove the script tag from `<head>` to keep
// the HTML somewhat consistent from the user's perspective. // the HTML somewhat consistent from the user's perspective.
for (const script of findChunkScripts(baseChunkUrl)){ for (const script of findChunkScripts(baseChunkUrl)){
script.remove(); script.remove();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment