Skip to content

Truly independent web browser

LibWeb: Fetch CSS images only for the elements that use them

sideshowbarker03ada6df57bf
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
index 83ad3c29cd1..41603f39f97 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
@@ -97,7 +97,6 @@ void web_css_grouping_rule_inserted(void* cell, NativeRule const* inserted)
auto* sheet = rule.parent_style_sheet();
if (!sheet)
return;
- sheet->invalidate_image_resource_registration();
if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(rule.native_rule().handle()))
record_style_rule_declarations_changed(RustRule { function }, *sheet);
else
diff --git a/Libraries/LibWeb/CSS/Invalidation/AdoptedStyleSheetInvalidator.cpp b/Libraries/LibWeb/CSS/Invalidation/AdoptedStyleSheetInvalidator.cpp
index 39598295188..30f0f8b0ec1 100644
--- a/Libraries/LibWeb/CSS/Invalidation/AdoptedStyleSheetInvalidator.cpp
+++ b/Libraries/LibWeb/CSS/Invalidation/AdoptedStyleSheetInvalidator.cpp
@@ -15,7 +15,6 @@ namespace Web::CSS::Invalidation {
void invalidate_style_after_adopting_style_sheet(DOM::Node& document_or_shadow_root, StyleSheetState& style_sheet)
{
style_sheet.add_owning_document_or_shadow_root(document_or_shadow_root);
- style_sheet.load_pending_image_resources(document_or_shadow_root.document());
// Evaluate the sheet's media queries before the next style update so the cascade can see its rules. Otherwise the
// rule cache may be rebuilt (e.g. via a :has() invalidation pass) before Document::evaluate_media_rules has a
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index 5887bc51dbf..759d19f983e 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -3017,7 +3017,6 @@ static RefPtr<SharedCompiledStyleSheet> shared_compiled_style_sheet_for(StyleShe
RuleCompilationContext context { style_engine, sheet_id, 0, document, style_computer };
compile_rules_into(context, *contents);
contents->evaluate_media_queries(document);
- contents->load_pending_image_resources(document);
auto shared_compiled_style_sheet = make_ref_counted<SharedCompiledStyleSheet>(move(key), move(contents), sheet_id);
shared_compiled_style_sheets.set(shared_compiled_style_sheet->key(), shared_compiled_style_sheet);
return shared_compiled_style_sheet;
diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cpp
index eb96863e346..095388e5c4e 100644
--- a/Libraries/LibWeb/CSS/StyleScope.cpp
+++ b/Libraries/LibWeb/CSS/StyleScope.cpp
@@ -109,8 +109,6 @@ void StyleScope::add_sheet(StyleSheetState& sheet, StyleEngineUpdate style_engin
{
sheet.add_owning_document_or_shadow_root(node());
- sheet.load_pending_image_resources(document());
-
insert_sheet_in_tree_order(sheet);
if (m_node->is_document())
document().fonts()->synchronize_css_connected_font_order();
diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.cpp b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
index 87c7ce686d4..a6ddcdd4c6b 100644
--- a/Libraries/LibWeb/CSS/StyleSheetImport.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
@@ -343,12 +343,6 @@ void StyleSheetImport::set_style_sheet(NonnullRefPtr<StyleSheetState> style_shee
m_style_sheet->add_owning_document_or_shadow_root(*owning_document_or_shadow_root);
}
- auto document = m_style_sheet->owning_document();
- if (!document && m_parent_style_sheet)
- document = m_parent_style_sheet->owning_document();
- if (document)
- m_style_sheet->load_pending_image_resources(*document);
-
// The rules the import brings in arrive now, at the position the import already holds.
if (m_parent_style_sheet)
record_imported_style_sheet_loaded(m_identity, *m_parent_style_sheet);
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cpp
index 7c14a0194f5..e0d4f217da3 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp
@@ -251,7 +251,6 @@ size_t StyleSheetState::external_memory_size() const
size = JS::saturating_add_external_memory_size(size, JS::hash_map_external_memory_size(m_imports));
size = JS::saturating_add_external_memory_size(size, JS::hash_table_external_memory_size(m_owning_documents_or_shadow_roots));
size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(m_critical_subresources));
- size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(m_pending_image_values));
return size;
}
@@ -325,7 +324,6 @@ GC::Ref<WebIDL::Promise> StyleSheetState::replace(Utf16String text)
auto rules = CSS::Parser::Parser { state.make_parsing_params() }.parse_as_stylesheet_contents(text);
rules.remove_imports();
state.set_rules(move(rules));
- state.invalidate_image_resource_registration();
record_stylesheet_rules_replaced(state);
state.invalidate_owners();
state.synchronize_fonts_after_rule_change();
@@ -348,7 +346,6 @@ void StyleSheetState::replace_rules(Utf16View text)
// 4. Set sheet’s CSS rules to rules.
set_rules(move(rules));
- invalidate_image_resource_registration();
record_stylesheet_rules_replaced(*this);
invalidate_owners();
@@ -445,7 +442,6 @@ void StyleSheetState::set_disabled(bool disabled)
if (document) {
if (has_document_owner())
document->font_computer().load_fonts_from_sheet(*this);
- load_pending_image_resources(*document);
}
} else if (document && has_document_owner()) {
document->font_computer().unload_fonts_from_sheet(*this);
@@ -563,42 +559,6 @@ Optional<::URL::URL> StyleSheetState::style_resource_base_url() const
return {};
}
-void StyleSheetState::load_pending_image_resources(DOM::Document& document)
-{
- if (disabled())
- return;
-
- // Keep image-bearing values alive only until the pending requests below have been started.
- // Their parsed data stays in the native rules; CSSOM wrappers do not own resource bindings.
- // NB: The process interns equal values, so a sheet repeating one image across its rules names
- // one value many times. Each is registered once, rather than with a wrapper per use.
- struct Context {
- StyleSheetState& sheet;
- HashTable<void const*> seen;
- Vector<NonnullRefPtr<StyleValue const>> images;
- } context { *this, {}, {} };
- // A constructed sheet can be adopted by many shadow roots in the same document. Discover
- // its images once, unless a rule-list mutation gives it new resources to register.
- if (exchange(m_needs_image_resource_registration, false)) {
- Parser::ValueParserFFI::rust_rule_list_visit_images(m_native_sheet.rules().handle(), &context, [](void* data, void const* value) {
- auto& context = *static_cast<Context*>(data);
- if (context.seen.set(value) != HashSetResult::InsertedNewEntry)
- return;
- auto image = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(value)));
- const_cast<StyleValue&>(*image).set_style_sheet(&context.sheet);
- context.images.append(move(image));
- });
- }
-
- auto pending = move(m_pending_image_values);
- for (auto const& weak_image_value : pending) {
- if (auto* image_value = weak_image_value.ptr()) {
- image_value->update_style_sheet_resource_context(*this);
- image_value->load_any_resources(document);
- }
- }
-}
-
// A sheet whose media stopped matching contributes nothing, so its declarations have to be taken
// back wherever they were winning, and given back when it matches again. Publishing the activation
// is separate from noticing the transition, because the two routes into a media change notice it in
@@ -697,7 +657,6 @@ void StyleSheetState::remove_css_connected_font_face(u64 rule_identity)
void StyleSheetState::recalculate_rule_caches()
{
- invalidate_image_resource_registration();
m_rule_cache = nullptr;
m_import_rules.clear();
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.h b/Libraries/LibWeb/CSS/StyleSheetState.h
index 6c47b31c6d8..da6414a3caa 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.h
+++ b/Libraries/LibWeb/CSS/StyleSheetState.h
@@ -141,9 +141,6 @@ public:
Optional<::URL::URL> base_url() const { return m_base_url; }
void set_base_url(Optional<::URL::URL> base_url) { m_base_url = move(base_url); }
- void register_pending_image_value(ImageStyleValue& value) { m_pending_image_values.append(value); }
- void invalidate_image_resource_registration() { m_needs_image_resource_registration = true; }
- void load_pending_image_resources(DOM::Document&);
Optional<::URL::URL> style_resource_base_url() const;
bool constructed() const { return m_native_sheet.flag(RustStyleSheet::Flag::Constructed); }
@@ -252,9 +249,6 @@ private:
Vector<StyleSheetImport&> m_critical_subresources;
- Vector<WeakPtr<ImageStyleValue>> m_pending_image_values;
- bool m_needs_image_resource_registration { true };
-
SheetID m_style_engine_sheet_id;
RefPtr<SharedCompiledStyleSheet> m_shared_compiled_style_sheet;
bool m_compiled_style_sheet_is_unshareable { false };
diff --git a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
index 54d7fac27a9..22575eb1796 100644
--- a/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/ImageStyleValue.cpp
@@ -216,10 +216,8 @@ void ImageStyleValue::set_style_sheet(StyleSheetState* style_sheet)
m_parent_style_sheet_origin_clean.clear();
m_should_absolutize_url_for_computed_value = false;
- if (style_sheet) {
+ if (style_sheet)
update_style_sheet_resource_context(*style_sheet);
- style_sheet->register_pending_image_value(*this);
- }
}
void ImageStyleValue::update_style_sheet_resource_context(StyleSheetState const& style_sheet)
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index b3ab946e2b8..f883c2adca6 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -3038,8 +3038,6 @@ static bool style_attribute_is_blocked_by_content_security_policy(Element& eleme
return ContentSecurityPolicy::should_elements_inline_type_behavior_be_blocked_by_content_security_policy(element, ContentSecurityPolicy::Directives::Directive::InlineType::StyleAttribute, value) == ContentSecurityPolicy::Directives::Directive::Result::Blocked;
}
-static void prefetch_inline_style_image_resources(CSS::CSSStyleProperties const&, Document&);
-
void Element::clone_inline_style_from(Element const& source)
{
// NB: A source whose style attribute still awaits its check leaves the copy to make that check once connected. So
@@ -3066,8 +3064,6 @@ void Element::inserted()
m_inline_style->set_declarations_from_text({});
else
CSS::Parser::ValueParserFFI::rust_declaration_block_destroy(exchange(m_inline_declarations, nullptr));
- } else if (CSS::Parser::ValueParserFFI::rust_declaration_block_has_abstract_image_values(inline_style_declarations())) {
- prefetch_inline_style_image_resources(*inline_style(), document());
}
}
}
@@ -6438,22 +6434,6 @@ Element::Directionality Element::parent_directionality() const
return Directionality::Ltr;
}
-static void prefetch_inline_style_image_resources(CSS::CSSStyleProperties const& inline_style, Document& document)
-{
- auto load_image_if_needed = [&](CSS::StyleValue const& value) {
- if (value.is_abstract_image())
- const_cast<CSS::AbstractImageStyleValue&>(value.as_abstract_image()).load_any_resources(document);
- };
- for (auto const& property : inline_style.properties()) {
- if (property.value->is_value_list()) {
- for (auto const& item : property.value->as_value_list().values())
- load_image_if_needed(*item);
- } else {
- load_image_if_needed(*property.value);
- }
- }
-}
-
// https://dom.spec.whatwg.org/#concept-element-attributes-change-ext
void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)
{
@@ -6608,10 +6588,6 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16
return;
}
set_inline_style_declarations_from_text(style_attribute_is_blocked_by_content_security_policy(*this, *value) ? Utf16View {} : *value);
- // NB: Asked first, so a block without images does not make views of its values. The CSSOM object of a block
- // with images holds the values that load them.
- if (CSS::Parser::ValueParserFFI::rust_declaration_block_has_abstract_image_values(inline_style_declarations()))
- prefetch_inline_style_image_resources(*inline_style(), document());
} else if (local_name == HTML::AttributeNames::dir || local_name == HTML::AttributeNames::lang) {
bool const is_dir = local_name == HTML::AttributeNames::dir;
if (is_dir) {
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 48d058d260c..efbdc44de32 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -957,6 +957,10 @@ void HTMLParserEndState::complete()
// Recheck its condition here and resume waiting using the same parser end state.
// INTEROP: Blink and WebKit recheck descendant completeness at their final load-completion gate. Gecko's
// document loader likewise remains busy while a child loader is waiting to complete.
+ // NB: A task that ran since step 8 can have given an element an image that starting layout fetches, and that
+ // fetch has to delay the load event too.
+ if (document->is_fully_active() && navigable_container_is_rendered(*document))
+ document->update_layout(DOM::UpdateLayoutReason::DocumentReadinessComplete);
if (document->is_fully_active() && document->anything_is_delaying_the_load_event()) {
state->m_phase = Phase::WaitingForLoadEventDelay;
state->schedule_progress_check();
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 0b1646bb85e..904849e9260 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -336,6 +336,7 @@ Text/input/SVG/svg-script-mutes-cross-origin-script-errors.html
; Observes stylesheet image requests through the HTTP test server.
Text/input/css/native-stylesheet-image-registration.html
+Text/input/css/background-images-are-fetched-only-when-used.html
; Form submission to /common/blank.html requires HTTP(s) scheme.
Text/input/wpt-import/custom-elements/form-associated/form-disabled-callback.html
diff --git a/Tests/LibWeb/Text/expected/css/background-images-are-fetched-only-when-used.txt b/Tests/LibWeb/Text/expected/css/background-images-are-fetched-only-when-used.txt
new file mode 100644
index 00000000000..8a3bbf70da7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/background-images-are-fetched-only-when-used.txt
@@ -0,0 +1,6 @@
+used requested: true
+unmatched requested: false
+hidden requested: false
+in-hidden-subtree requested: false
+overridden requested: false
+inline-hidden requested: false
diff --git a/Tests/LibWeb/Text/expected/css/native-stylesheet-image-registration.txt b/Tests/LibWeb/Text/expected/css/native-stylesheet-image-registration.txt
index 1b7f0c59dc6..6fae6675b37 100644
--- a/Tests/LibWeb/Text/expected/css/native-stylesheet-image-registration.txt
+++ b/Tests/LibWeb/Text/expected/css/native-stylesheet-image-registration.txt
@@ -1,4 +1,4 @@
discarded requested: false
-initial requested: true
-inserted requested: true
+initial requested: false
+inserted requested: false
replaced requested: true
diff --git a/Tests/LibWeb/Text/input/css/background-images-are-fetched-only-when-used.html b/Tests/LibWeb/Text/input/css/background-images-are-fetched-only-when-used.html
new file mode 100644
index 00000000000..808d28dc336
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/background-images-are-fetched-only-when-used.html
@@ -0,0 +1,50 @@
+<!doctype html>
+<script src="../include.js"></script>
+<body>
+<div class="used"></div>
+<div class="hidden"></div>
+<div class="hidden-parent"><div class="in-hidden-subtree"></div></div>
+<div class="overridden winner"></div>
+<div id="inline-hidden"></div>
+<script>
+const token = crypto.randomUUID();
+const names = ["used", "unmatched", "hidden", "in-hidden-subtree", "overridden", "inline-hidden"];
+const pathOf = name => `/echo/css-image-${token}-${name}.png`;
+for (const name of names) {
+ const request = new XMLHttpRequest();
+ request.open("POST", "/echo", false);
+ request.setRequestHeader("Content-Type", "application/json");
+ request.send(JSON.stringify({
+ method: "GET",
+ path: pathOf(name),
+ status: 200,
+ headers: { "Content-Type": "image/png", "Cache-Control": "no-store" },
+ body_encoding: "base64",
+ body: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=",
+ }));
+}
+
+const style = document.createElement("style");
+style.textContent = `
+ div { width: 10px; height: 10px; }
+ .used { background-image: url("${pathOf("used")}"); }
+ .unmatched { background-image: url("${pathOf("unmatched")}"); }
+ .hidden { display: none; background-image: url("${pathOf("hidden")}"); }
+ .hidden-parent { display: none; }
+ .in-hidden-subtree { background-image: url("${pathOf("in-hidden-subtree")}"); }
+ .overridden { background-image: url("${pathOf("overridden")}"); }
+ .overridden.winner { background-image: url("${pathOf("used")}"); }
+`;
+document.head.append(style);
+document.getElementById("inline-hidden").setAttribute("style", `display: none; background-image: url("${pathOf("inline-hidden")}")`);
+
+asyncTest(done => {
+ window.addEventListener("load", async () => {
+ for (const name of names) {
+ const response = await fetch(`/recorded-request-headers${pathOf(name)}`);
+ println(`${name} requested: ${response.ok}`);
+ }
+ done();
+ });
+});
+</script>
diff --git a/Tests/LibWeb/Text/input/css/native-stylesheet-image-registration.html b/Tests/LibWeb/Text/input/css/native-stylesheet-image-registration.html
index c4bc974dd8a..4068ff9bb2e 100644
--- a/Tests/LibWeb/Text/input/css/native-stylesheet-image-registration.html
+++ b/Tests/LibWeb/Text/input/css/native-stylesheet-image-registration.html
@@ -1,5 +1,6 @@
<!doctype html>
<script src="../include.js"></script>
+<div class="使用中" style="width: 10px; height: 10px"></div>
<script>
const token = crypto.randomUUID();
const paths = ["discarded", "initial", "inserted", "replaced"].map(name => `/echo/native-sheet-image-${token}-${name}.png`);
@@ -17,13 +18,13 @@ for (const path of paths) {
}));
}
-const source = path => `@media not all { .未使用 { background-image: url("${path}"); } }`;
+const source = path => `@media all { .使用中 { background-image: url("${path}"); } }`;
const sheet = new CSSStyleSheet({ disabled: true });
sheet.replaceSync(source(paths[0]));
document.adoptedStyleSheets = [sheet];
sheet.replaceSync(source(paths[1]));
sheet.disabled = false;
-sheet.cssRules[0].insertRule(`.追加 { background-image: url("${paths[2]}"); }`, 1);
+sheet.cssRules[0].insertRule(`.使用中 { background-image: url("${paths[2]}"); }`, 1);
sheet.disabled = true;
sheet.disabled = false;
sheet.replaceSync(source(paths[3]));
@@ -32,8 +33,7 @@ sheet.disabled = false;
asyncTest(done => {
window.addEventListener("load", async () => {
- // Attachment requests delay load, even though these selectors never match. No timer or
- // rendered image is needed to observe resource registration after each rule-list change.
+ // Only the image the element has when it's laid out is requested, whatever the rule list held before.
for (const [index, path] of paths.entries()) {
const response = await fetch(`/recorded-request-headers${path}`);
println(`${["discarded", "initial", "inserted", "replaced"][index]} requested: ${response.ok}`);