LibWeb: Replace spin_until in execute_script with deferred parser start

HTMLScriptElement::execute_script() and SVGScriptElement had spin_until
calls waiting for ready_to_run_scripts to become true. The race exists
because load_html_document() resolves the session history signal and
starts the parser in the same deferred_invoke — so the parser can hit a
<script> before update_for_history_step_application() sets the flag.

Instead of spinning, defer parser->run() until the document is ready.
Document gains a m_deferred_parser_start callback that is invoked when
set_ready_to_run_scripts() is called. The callback is cleared before
invocation to avoid reentrancy issues (parser->run() can synchronously
execute scripts). All three document loading paths (HTML, XML, text)
now check ready_to_run_scripts before starting the parser and defer if
needed.

create_document_for_inline_content() (used for error pages) now calls
set_ready_to_run_scripts() before mutating the document, ensuring the
invariant holds for all parser paths.

The spin_until calls are replaced with VERIFY assertions.
This commit is contained in:
Aliaksandr Kalenik 2026-03-29 00:17:41 +01:00 committed by Alexander Kalenik
parent df96b69e7a
commit 76d9cc4baf
Notes: github-actions[bot] 2026-03-29 00:06:28 +00:00
6 changed files with 68 additions and 31 deletions

View file

@ -122,8 +122,7 @@ void HTMLScriptElement::execute_script()
{
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html
// Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document.
if (!m_document->ready_to_run_scripts())
main_thread_event_loop().spin_until(GC::create_function(heap(), [&] { return m_document->ready_to_run_scripts(); }));
VERIFY(document().ready_to_run_scripts());
// 1. Let document be el's node document.
GC::Ref<DOM::Document> document = this->document();