Skip to content

Refactor addSpeculationRules to Return Individual DOM References for Removability #442

Closed
@giorgiopellegrino

Description

@giorgiopellegrino

Description

The addSpeculationRules function should support dynamic addition and removal of speculation rules in alignment with recent platform capabilities.

Motivation

The current implementation adds all URLs in a single <script type="speculationrules"> element. However, with support for removing speculation rules based on viewport visibility, it's more effective to:

  • Insert one speculation rule per URL.
  • Return a structured response linking each URL to its corresponding DOM element, allowing the caller to remove individual rules without querying the DOM.

Changes to introduce

  • For each URL, a separate speculation rule script should be created and appended to the document.
  • The function should return an array of Maps in the format:
{
  "/page1": HTMLScriptElement,
  "/page2": HTMLScriptElement,
  ...
}

Example Usage

const urls = addSpeculationRules(["/page1", "/page2"], "eager");
document.head.removeChild(urls["/page1"]);

This approach improves clarity and simplifies DOM cleanup when rules are no longer needed.

cc @gilbertococchi @addyosmani

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions