Skip to content

Truly independent web browser

LibWeb: Reuse compiled scripts across loads in a process

Andreas Kling85532751fc7b
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 50804f155e8..85099c3a01a 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -576,6 +576,7 @@ set(SOURCES
HTML/SanitizerConfiguration.cpp
HTML/Scripting/Agent.cpp
HTML/Scripting/ClassicScript.cpp
+ HTML/Scripting/CompiledScriptCache.cpp
HTML/Scripting/ConsoleInputCompletion.cpp
HTML/Scripting/DevToolsLoggedObjects.cpp
HTML/Scripting/DevToolsObjectTable.cpp
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index a3f6b27c6ec..0e4244ea543 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -59,6 +59,7 @@
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/PreloadEntry.h>
#include <LibWeb/HTML/Scripting/Agent.h>
+#include <LibWeb/HTML/Scripting/CompiledScriptCache.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
@@ -213,15 +214,20 @@ private:
HashMap<Utf16String, NonnullRefPtr<HTTP::MemoryCache>> m_cache;
};
-// https://fetch.spec.whatwg.org/#determine-the-http-cache-partition
-static RefPtr<HTTP::MemoryCache> determine_the_http_cache_partition(Infrastructure::Request const& request)
+Optional<Utf16String> http_cache_partition(Infrastructure::Request const& request)
{
- // 1. Let key be the result of determining the network partition key given request.
auto key = Infrastructure::determine_the_network_partition_key(request);
// NB: We partition this cache like RequestServer's disk cache, which a request from a document with an opaque
// origin does not use.
- auto partition = key.has_value() ? key->disk_cache_partition() : OptionalNone {};
+ return key.has_value() ? key->disk_cache_partition() : OptionalNone {};
+}
+
+// https://fetch.spec.whatwg.org/#determine-the-http-cache-partition
+static RefPtr<HTTP::MemoryCache> determine_the_http_cache_partition(Infrastructure::Request const& request)
+{
+ // 1. Let key be the result of determining the network partition key given request.
+ auto partition = http_cache_partition(request);
// 2. If key is null, then return null.
if (!partition.has_value())
@@ -3545,6 +3551,7 @@ bool http_memory_cache_enabled()
void clear_http_memory_cache()
{
HTTPCache::the().clear_cache();
+ HTML::CompiledScriptCache::the().clear();
}
void update_javascript_bytecode_cache_in_http_memory_cache(Utf16String const& partition, URL::URL const& url, ByteString const& method, HTTP::HeaderList const& request_headers, u64 vary_key, Core::ImmutableBytes javascript_bytecode_cache)
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.h b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
index df7ca4da4e9..fa6f6c3d7c7 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.h
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.h
@@ -72,6 +72,7 @@ void append_user_agent_client_hints_for_request(Infrastructure::Request&);
WEB_API void set_http_memory_cache_enabled(bool enabled);
WEB_API bool http_memory_cache_enabled();
WEB_API void clear_http_memory_cache();
+WEB_API Optional<Utf16String> http_cache_partition(Infrastructure::Request const&);
WEB_API void set_disk_cache_enabled_for_navigations_for_testing(bool enabled);
WEB_API bool disk_cache_enabled_for_navigations_for_testing();
void update_javascript_bytecode_cache_in_http_memory_cache(Utf16String const& partition, URL::URL const&, ByteString const& method, HTTP::HeaderList const& request_headers, u64 vary_key, Core::ImmutableBytes);
diff --git a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp
new file mode 100644
index 00000000000..413054464dc
--- /dev/null
+++ b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/NeverDestroyed.h>
+#include <AK/NumericLimits.h>
+#include <LibWeb/HTML/Scripting/CompiledScriptCache.h>
+
+namespace Web::HTML {
+
+// FIXME: This limit is a guess. It has not been measured against what real sites compile to.
+static constexpr size_t compiled_script_cache_size_limit = 128 * MiB;
+
+CompiledScriptCache& CompiledScriptCache::the()
+{
+ static NeverDestroyed<CompiledScriptCache> cache;
+ return *cache;
+}
+
+Optional<JS::CompiledProgram> CompiledScriptCache::find(CompiledScriptCacheKey const& key, Utf16String const& source_text)
+{
+ auto entry = m_entries.get(key);
+ if (!entry.has_value() || entry->source_text != source_text)
+ return {};
+
+ entry->touch_serial = ++m_next_touch_serial;
+ auto program = entry->program.clone();
+
+ // NB: Entries grow as their functions compile, which no store sees.
+ evict_until_within_limit();
+ return program;
+}
+
+void CompiledScriptCache::store(CompiledScriptCacheKey key, Utf16String source_text, JS::CompiledProgram const& program)
+{
+ if (auto entry = m_entries.get(key); entry.has_value())
+ release(*entry);
+
+ program.set_retains_compiled_functions(true);
+ m_entries.set(move(key), Entry { move(source_text), program.clone(), ++m_next_touch_serial });
+ evict_until_within_limit();
+}
+
+void CompiledScriptCache::clear()
+{
+ for (auto& it : m_entries)
+ release(it.value);
+ m_entries.clear();
+}
+
+void CompiledScriptCache::release(Entry& entry)
+{
+ // NB: Realms that still run the program have no use for keeping the functions they compile from here on.
+ entry.program.set_retains_compiled_functions(false);
+}
+
+void CompiledScriptCache::evict_until_within_limit()
+{
+ size_t size = 0;
+ for (auto const& it : m_entries)
+ size += it.value.program.memory_size();
+
+ while (size > compiled_script_cache_size_limit) {
+ Optional<CompiledScriptCacheKey const&> least_recently_used_key;
+ u64 least_recently_used_serial = NumericLimits<u64>::max();
+ for (auto const& it : m_entries) {
+ if (it.value.touch_serial >= least_recently_used_serial)
+ continue;
+ least_recently_used_key = it.key;
+ least_recently_used_serial = it.value.touch_serial;
+ }
+ VERIFY(least_recently_used_key.has_value());
+
+ auto entry = m_entries.take(*least_recently_used_key);
+ size -= entry->program.memory_size();
+ release(*entry);
+ }
+}
+
+}
diff --git a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h
new file mode 100644
index 00000000000..b961771263b
--- /dev/null
+++ b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Traits.h>
+#include <AK/Utf16String.h>
+#include <LibJS/ScriptCompilation.h>
+#include <LibWeb/Export.h>
+
+namespace Web::HTML {
+
+// What a compiled script is stored under. The filename, base URL and muted errors of a script belong to one load of it
+// and are not part of its compiled code.
+struct CompiledScriptCacheKey {
+ Utf16String partition;
+ String url_without_fragment;
+ JS::ProgramType program_type { JS::ProgramType::Script };
+ size_t line_number_offset { 0 };
+
+ bool operator==(CompiledScriptCacheKey const&) const = default;
+};
+
+// The compiled scripts of this process, which a script that loads again links into its own realm instead of being
+// parsed and compiled again. Entries are found after a fetch completed, by the decoded source text the fetch came up
+// with, so they answer nothing that the checks of a fetch decide, and can not stand in for different source text.
+class WEB_API CompiledScriptCache {
+public:
+ static CompiledScriptCache& the();
+
+ Optional<JS::CompiledProgram> find(CompiledScriptCacheKey const&, Utf16String const& source_text);
+
+ // From here on, the program keeps the functions that get compiled for it. Replaces what the key held before.
+ void store(CompiledScriptCacheKey, Utf16String source_text, JS::CompiledProgram const&);
+
+ void clear();
+
+private:
+ struct Entry {
+ Utf16String source_text;
+ JS::CompiledProgram program;
+ u64 touch_serial { 0 };
+ };
+
+ static void release(Entry&);
+
+ void evict_until_within_limit();
+
+ HashMap<CompiledScriptCacheKey, Entry> m_entries;
+ u64 m_next_touch_serial { 0 };
+};
+
+}
+
+template<>
+struct AK::Traits<Web::HTML::CompiledScriptCacheKey> : public AK::DefaultTraits<Web::HTML::CompiledScriptCacheKey> {
+ static unsigned hash(Web::HTML::CompiledScriptCacheKey const& key)
+ {
+ auto hash = pair_int_hash(key.partition.hash(), key.url_without_fragment.hash());
+ hash = pair_int_hash(hash, to_underlying(key.program_type));
+ return pair_int_hash(hash, u64_hash(key.line_number_offset));
+ }
+};
diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
index ab122833820..612dcabaa55 100644
--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp
@@ -12,6 +12,7 @@
#include <LibGC/Function.h>
#include <LibGC/Heap.h>
#include <LibGC/Root.h>
+#include <LibHTTP/Cache/Utilities.h>
#include <LibJS/Runtime/ModuleRequest.h>
#include <LibJS/ScriptCompilation.h>
#include <LibJS/SourceCode.h>
@@ -31,6 +32,7 @@
#include <LibWeb/HTML/HTMLScriptElement.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
#include <LibWeb/HTML/Scripting/ClassicScript.h>
+#include <LibWeb/HTML/Scripting/CompiledScriptCache.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/HTML/Scripting/ModuleScript.h>
@@ -60,6 +62,27 @@ static ByteBuffer take_body_bytes_as_byte_buffer(Fetch::Infrastructure::FetchAlg
return body_bytes.get<Core::ImmutableBytes>().copy_to_byte_buffer().release_value_but_fixme_should_propagate_errors();
}
+// The key that a script compiled from a response is stored under, if the rules of HTTP caching let a cache store the
+// response, and the request has a partition to store it in.
+static Optional<CompiledScriptCacheKey> compiled_script_cache_key(Fetch::Infrastructure::Request const& request, URL::URL const& url, u32 status_code, HTTP::HeaderList const& response_headers, JS::ProgramType type, size_t line_number_offset)
+{
+ if (!Fetch::Fetching::http_memory_cache_enabled() || request.cache_mode() == HTTP::CacheMode::NoStore)
+ return {};
+ if (!HTTP::is_cacheable(request.method(), request.header_list()) || !HTTP::is_cacheable(status_code, response_headers))
+ return {};
+
+ auto partition = Fetch::Fetching::http_cache_partition(request);
+ if (!partition.has_value())
+ return {};
+
+ return CompiledScriptCacheKey {
+ .partition = partition.release_value(),
+ .url_without_fragment = HTTP::serialize_url_for_cache_storage(url),
+ .program_type = type,
+ .line_number_offset = line_number_offset,
+ };
+}
+
// Submit parsing and top-level bytecode generation to the thread pool, then bounce back to the main thread via
// deferred_invoke once the worker is done, and on to a task of the settings object's global there. Syntax errors still
// come back as a ParsedProgram so the main thread can report them through the same Script/ModuleScript construction
@@ -67,11 +90,15 @@ static ByteBuffer take_body_bytes_as_byte_buffer(Fetch::Infrastructure::FetchAlg
// still happen on the main thread.
// NB: The SourceCode stays on the main thread inside the heap-allocated callback. The worker thread only receives its
// code, which is thread-safe to share.
-static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnullRefPtr<JS::SourceCode const> source_code, JS::ProgramType type, size_t line_number_offset, Function<void(OffThreadCompiledProgram, NonnullRefPtr<JS::SourceCode const>)> on_compiled)
+// With a cache key, a program that the cache of compiled scripts has for the source code skips all of this, and
+// otherwise the program goes there before anything runs it.
+static void compile_off_thread(EnvironmentSettingsObject& settings_object, NonnullRefPtr<JS::SourceCode const> source_code, JS::ProgramType type, size_t line_number_offset, Optional<CompiledScriptCacheKey> cache_key, Function<void(OffThreadCompiledProgram, NonnullRefPtr<JS::SourceCode const>)> on_compiled)
{
// Take the code the parser needs while still on the main thread.
auto source_text = source_code->code();
+ auto cached_program = cache_key.has_value() ? CompiledScriptCache::the().find(*cache_key, source_text) : OptionalNone {};
+
// Capture source_code in the callback so it stays alive on the main thread and is available for materialization.
// The script runs in a task of the settings object's global, so never beside a rendering update in flight that holds
// back the tasks of its document, and the microtasks it queues (e.g. promise reactions from react_to_promise during
@@ -86,14 +113,28 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Nonnu
}));
});
+ if (cached_program.has_value()) {
+ (*callback)(OffThreadCompiledProgram { .compiled = cached_program.release_value() });
+ delete callback;
+ return;
+ }
+
auto& main_thread_event_loop = Core::EventLoop::current();
- Threading::ThreadPool::the().submit([source_text = move(source_text), type, line_number_offset, callback, &main_thread_event_loop]() mutable {
- OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(move(source_text), type, line_number_offset) };
+ Threading::ThreadPool::the().submit([source_text = move(source_text), type, line_number_offset, cache_key = move(cache_key), callback, &main_thread_event_loop]() mutable {
+ OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(source_text, type, line_number_offset) };
if (result.parsed && !result.parsed.has_errors())
result.compiled = JS::CompiledProgram::compile(move(result.parsed));
- main_thread_event_loop.deferred_invoke([result = move(result), callback]() mutable {
+ main_thread_event_loop.deferred_invoke([result = move(result), source_text = move(source_text), cache_key = move(cache_key), callback]() mutable {
+ if (cache_key.has_value() && result.compiled) {
+ // NB: Another load of the script may have stored it while this one compiled.
+ if (auto cached_program = CompiledScriptCache::the().find(*cache_key, source_text); cached_program.has_value())
+ result.compiled = cached_program.release_value();
+ else
+ CompiledScriptCache::the().store(cache_key.release_value(), move(source_text), result.compiled);
+ }
+
(*callback)(move(result));
delete callback;
});
@@ -465,7 +506,9 @@ void fetch_classic_script(JS::Realm& realm, URL::URL const& url, EnvironmentSett
auto filename = request->url().to_byte_string();
auto source_code = JS::SourceCode::create(utf16_string_from_url_ascii(filename.view()), move(source_text));
- compile_off_thread(settings_object, move(source_code), JS::ProgramType::Script, 1,
+ auto cache_key = compiled_script_cache_key(request, request->url(), response->status(), response->header_list(), JS::ProgramType::Script, 1);
+
+ compile_off_thread(settings_object, move(source_code), JS::ProgramType::Script, 1, move(cache_key),
[response_url = move(response_url), filename = move(filename),
muted_errors, on_complete_root = move(on_complete_root),
settings_root = move(settings_root)](auto result, auto source_code) mutable {
@@ -835,7 +878,9 @@ void fetch_single_module_script(JS::Realm& realm,
auto module_type_string = module_type;
auto source_code = JS::SourceCode::create(utf16_string_from_url_ascii(url_string.view()), move(source_text));
- compile_off_thread(settings_object, move(source_code), JS::ProgramType::Module, 0,
+ auto cache_key = compiled_script_cache_key(request, url, internal_response->status(), internal_response->header_list(), JS::ProgramType::Module, 0);
+
+ compile_off_thread(settings_object, move(source_code), JS::ProgramType::Module, 0, move(cache_key),
[url = move(url), url_string = move(url_string), response_url = move(response_url),
module_type_string = move(module_type_string),
options, settings_root = move(settings_root)](auto result, auto source_code) mutable {