Truly independent web browser
LibWeb: Don’t delay the load event for a lazy image’s resumed fetch
sideshowbarker9200854b028f
diff --git a/Libraries/LibWeb/CSS/Fetch.cpp b/Libraries/LibWeb/CSS/Fetch.cppindex 245788d43e1..4613c80b5aa 100644--- a/Libraries/LibWeb/CSS/Fetch.cpp+++ b/Libraries/LibWeb/CSS/Fetch.cpp@@ -180,6 +180,9 @@ GC::Ptr<HTML::SharedResourceRequest> fetch_an_external_image_for_a_stylesheet(Stauto shared_resource_request = HTML::SharedResourceRequest::get_or_create(document, *request);+ // NB: A stylesheet's image waits for the fetch without callbacks, or adds them only once the fetch has started,+ // including a fetch that another user already started.+ shared_resource_request->wait_without_callbacks();if (shared_resource_request->needs_fetching())shared_resource_request->fetch_resource(*request);diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cppindex 0480757cf68..1f99b407379 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp@@ -1254,7 +1254,8 @@ after_step_7:if (delay_load_event)m_load_event_delayer.emplace(document());- add_callbacks_to_image_request(*image_request, maybe_omit_events, url_string->utf16_view(), previous_url.utf16_view());+ add_callbacks_to_image_request(*image_request, maybe_omit_events, url_string->utf16_view(), previous_url.utf16_view(),+ delay_load_event ? SharedResourceRequest::DelaysLoadEvent::Yes : SharedResourceRequest::DelaysLoadEvent::No);// AD-HOC: If the image request is already available or fetching, no need to start another fetch.if (image_request->is_available() || image_request->is_fetching())@@ -1310,7 +1311,7 @@ after_step_7:}));}-void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> image_request, bool maybe_omit_events, Utf16View url_string, Utf16View previous_url)+void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> image_request, bool maybe_omit_events, Utf16View url_string, Utf16View previous_url, SharedResourceRequest::DelaysLoadEvent delays_load_event){auto captured_url_string = Utf16String::from_utf16(url_string);auto captured_previous_url = Utf16String::from_utf16(previous_url);@@ -1422,7 +1423,8 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imag},[this] {m_load_event_delayer.clear();- });+ },+ delays_load_event);}// NB: Aborting the image requests aborts their fetches, so nothing that the img element is fetching delays the loaddiff --git a/Libraries/LibWeb/HTML/HTMLImageElement.h b/Libraries/LibWeb/HTML/HTMLImageElement.hindex 15fd717b6ef..07dc82c45e0 100644--- a/Libraries/LibWeb/HTML/HTMLImageElement.h+++ b/Libraries/LibWeb/HTML/HTMLImageElement.h@@ -20,6 +20,7 @@#include <LibWeb/HTML/DecodedImageData.h>#include <LibWeb/HTML/HTMLElement.h>#include <LibWeb/HTML/LazyLoadingElement.h>+#include <LibWeb/HTML/SharedResourceRequest.h>#include <LibWeb/HTML/SourceSet.h>#include <LibWeb/Layout/ImageProvider.h>@@ -161,7 +162,7 @@ private:virtual void did_set_viewport_rect(CSSPixelRect const&) override;void handle_failed_fetch();- void add_callbacks_to_image_request(GC::Ref<ImageRequest>, bool maybe_omit_events, Utf16View url_string, Utf16View previous_url);+ void add_callbacks_to_image_request(GC::Ref<ImageRequest>, bool maybe_omit_events, Utf16View url_string, Utf16View previous_url, SharedResourceRequest::DelaysLoadEvent);void stop_delaying_the_load_event_for_aborted_requests();void create_alt_text_shadow_tree();diff --git a/Libraries/LibWeb/HTML/ImageRequest.cpp b/Libraries/LibWeb/HTML/ImageRequest.cppindex ed4c4c6eaaf..eb05444d43b 100644--- a/Libraries/LibWeb/HTML/ImageRequest.cpp+++ b/Libraries/LibWeb/HTML/ImageRequest.cpp@@ -131,10 +131,10 @@ void ImageRequest::fetch_image(NonnullRefPtr<Fetch::Infrastructure::Request> reqm_shared_resource_request->fetch_resource(request);}-void ImageRequest::add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop)+void ImageRequest::add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop, SharedResourceRequest::DelaysLoadEvent delays_load_event){VERIFY(m_shared_resource_request);- if (auto id = m_shared_resource_request->add_removable_callbacks(move(on_finish), move(on_fail), move(on_stop)); id.has_value())+ if (auto id = m_shared_resource_request->add_removable_callbacks(move(on_finish), move(on_fail), move(on_stop), delays_load_event); id.has_value())m_shared_resource_request_callbacks_ids.append(*id);}diff --git a/Libraries/LibWeb/HTML/ImageRequest.h b/Libraries/LibWeb/HTML/ImageRequest.hindex f70020443c3..721ed905af2 100644--- a/Libraries/LibWeb/HTML/ImageRequest.h+++ b/Libraries/LibWeb/HTML/ImageRequest.h@@ -14,6 +14,7 @@#include <LibURL/URL.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/CORSSettingAttribute.h>+#include <LibWeb/HTML/SharedResourceRequest.h>namespace Web::HTML {@@ -58,7 +59,7 @@ public:void prepare_for_presentation(HTMLImageElement&);void fetch_image(NonnullRefPtr<Fetch::Infrastructure::Request>);- void add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {});+ void add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {}, SharedResourceRequest::DelaysLoadEvent = SharedResourceRequest::DelaysLoadEvent::Yes);// Adds callbacks that do not make the fetch delay the load event, and that stop_waiting_for_fetch() keeps.void add_callbacks_without_delaying_the_load_event(Function<void()> on_finish, Function<void()> on_fail);diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp b/Libraries/LibWeb/HTML/SharedResourceRequest.cppindex e6c5700b913..edeb1e6ab8a 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.cpp+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.cpp@@ -196,8 +196,12 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::};m_state = State::Fetching;- m_load_event_delayer.emplace(*m_document);- m_fetch_has_user_without_callbacks = m_callbacks.is_empty();+ // NB: A user that waits for the fetch decides if the fetch delays the load event; a lazy image's callbacks don't.+ auto some_waiter_delays = any_of(m_callbacks, [](auto const& callbacks) {+ return callbacks.id != 0 && callbacks.delays_load_event == DelaysLoadEvent::Yes;+ });+ if (m_fetch_has_user_without_callbacks || some_waiter_delays)+ m_load_event_delayer.emplace(*m_document);auto fetch_controller = Fetch::Fetching::fetch(realm,@@ -211,6 +215,13 @@ void SharedResourceRequest::fetch_resource(NonnullRefPtr<Fetch::Infrastructure::set_fetch_controller(fetch_controller);}+void SharedResourceRequest::wait_without_callbacks()+{+ m_fetch_has_user_without_callbacks = true;+ if (m_state == State::Fetching && !m_load_event_delayer.has_value())+ m_load_event_delayer.emplace(*m_document);+}+void SharedResourceRequest::add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop){(void)add_removable_callbacks(move(on_finish), move(on_fail), move(on_stop));diff --git a/Libraries/LibWeb/HTML/SharedResourceRequest.h b/Libraries/LibWeb/HTML/SharedResourceRequest.hindex 614e4203e3d..845b1329f18 100644--- a/Libraries/LibWeb/HTML/SharedResourceRequest.h+++ b/Libraries/LibWeb/HTML/SharedResourceRequest.h@@ -51,6 +51,9 @@ public:void fetch_resource(NonnullRefPtr<Fetch::Infrastructure::Request>);+ // Records a user that waits for the fetch without callbacks, so that the fetch delays the load event for it.+ void wait_without_callbacks();+void add_callbacks(Function<void()> on_finish, Function<void()> on_fail, Function<void()> on_stop = {});enum class DelaysLoadEvent : u8 {@@ -107,7 +110,7 @@ private:Vector<Callbacks> m_callbacks;u64 m_next_callbacks_id { 1 };- // NB: Set when the fetch was started for a user that waits for it without callbacks.+ // NB: Set once a user waits for the fetch without callbacks.bool m_fetch_has_user_without_callbacks { false };Key m_key;diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 39c9120482d..19079a68fd9 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -115,6 +115,7 @@ Text/input/SiteIsolation/popup-opened-onto-a-coop-page-leaves-its-opener.htmlText/input/wpt-import/html/semantics/embedded-content/the-img-element/image-loading-lazy-below-viewport-dynamic.htmlText/input/HTML/lazy-image-eager-after-adoption.htmlText/input/HTML/lazy-image-eager-after-source-change.html+Text/input/HTML/lazy-image-made-eager-does-not-delay-load-event.htmlText/input/HTML/lazy-image-eager-with-retained-pending-request.htmlText/input/wpt-import/html/semantics/embedded-content/the-img-element/image-loading-lazy-to-eager.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/lazy-image-made-eager-does-not-delay-load-event.txt b/Tests/LibWeb/Text/expected/HTML/lazy-image-made-eager-does-not-delay-load-event.txtnew file mode 100644index 00000000000..c3c523fb169--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/lazy-image-made-eager-does-not-delay-load-event.txt@@ -0,0 +1,2 @@+Load event fired while the image was loading: true+Image loaded once unblocked: truediff --git a/Tests/LibWeb/Text/input/HTML/lazy-image-made-eager-does-not-delay-load-event.html b/Tests/LibWeb/Text/input/HTML/lazy-image-made-eager-does-not-delay-load-event.htmlnew file mode 100644index 00000000000..35f20157825--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/lazy-image-made-eager-does-not-delay-load-event.html@@ -0,0 +1,49 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const server = httpTestServer();+ const token = uniqueID();+ const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";+ const image = await server.createEcho("GET", `/lazy-made-eager-${token}.png`, {+ status: 200,+ headers: { "Content-Type": "image/png", "Cache-Control": "no-store" },+ body: png,+ body_encoding: "base64",+ wait_for_unblock: token,+ });+ const frame = document.createElement("iframe");+ let resolveLoaded, resolveImageLoaded;+ const loaded = new Promise(resolve => (resolveLoaded = resolve));+ const imageLoaded = new Promise(resolve => (resolveImageLoaded = resolve));+ const onMessage = event => {+ if (event.source !== frame.contentWindow || event.data.token !== token) return;+ if (event.data.kind === "loaded") resolveLoaded(event.data);+ if (event.data.kind === "image") resolveImageLoaded(event.data);+ };+ addEventListener("message", onMessage);+ // NB: The image is lazy when its source is first processed, so its fetch must not delay the load event, even+ // though the image becomes eager before the document has finished loading.+ frame.srcdoc = `<!doctype html><body>+ <div style="height: 10000px"></div>+ <img id="image" src=${JSON.stringify(image)} loading="lazy">+ <script>+ const send = (kind, data) => parent.postMessage({ token: ${JSON.stringify(token)}, kind, ...data }, "*");+ image.onload = () => send("image", { width: image.naturalWidth });+ addEventListener("load", () => send("loaded", { complete: image.complete }), { once: true });+ image.loading = "eager";+ <\/script>`;+ document.body.appendChild(frame);+ try {+ const result = await loaded;+ println(`Load event fired while the image was loading: ${!result.complete}`);+ await fetch(new URL(`/unblock/${token}`, image));+ const imageResult = await imageLoaded;+ println(`Image loaded once unblocked: ${imageResult.width === 1}`);+ } finally {+ await fetch(new URL(`/unblock/${token}`, image));+ removeEventListener("message", onMessage);+ frame.remove();+ }+ });+</script>