`StyleInjector` prepends a stylesheet with `@layer`, forcing a full style and layout rebuild at drag start

Open Beginner friendly
#2,199 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
65/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
css, typescript

Research direction

The document path is in StyleInjector in @dnd-kit/dom: find the root.head.prepend(style) calls and the MutationObserver branch that re-inserts a removed style. Run the standalone reproduction from the issue to confirm the prepend cost, then switch to append and verify that @layer dnd-kit still has lower priority than the page's layers — that ordering question is the real work, and the issue lists the options. Done means the package tests pass and drag-start timing improves without changing cascade priority.

Written by the indexing model from the issue text.

Description

Repository: clauderic/dnd-kit · Package: @dnd-kit/dom 0.5.3 (latest) · Browser: Chromium 158.0.8127.18 (Playwright 1.65), Chrome on macOS

Summary

StyleInjector inserts its <style> elements with root.head.prepend(style) (and re-prepends them if removed), so that its @layer dnd-kit { … } rules come first and get the lowest cascade priority. When a page already uses cascade layers (every Tailwind v4 app does), inserting a stylesheet that contains @layer ahead of the existing sheets makes the browser rebuild every style on the page and lay it out again. Appending the same sheet costs almost nothing.

The Feedback plugin's rules are inserted at the first drag on each page (they're retained afterwards since #2141), so the first drag after every page load pays for the rebuild inside the drag-start task.

Minimal reproduction (standalone, no dnd-kit needed)

Save as repro.html and open it in Chrome; it prints the median of 9 runs. ~10,000 elements; the page uses @layer and @property, like a Tailwind v4 app.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Prepending a stylesheet that declares @layer</title>
    <style>
      /* A page styled the way a Tailwind v4 app is: cascade layers and registered custom properties. */
      @layer base, components, utilities;
      @property --x1 {
        syntax: "<length>";
        inherits: false;
        initial-value: 0px;
      }
      @property --x2 {
        syntax: "<color>";
        inherits: false;
        initial-value: transparent;
      }
      @property --x3 {
        syntax: "<number>";
        inherits: false;
        initial-value: 0;
      }
      @layer base {
        body {
          font-family: system-ui, sans-serif;
        }
      }
      @layer components {
        .card {
          padding: 8px;
          border: 1px solid #ccc;
          margin: 4px;
        }
      }
      @layer utilities {
        .muted {
          color: #666;
        }
        .row {
          display: flex;
          gap: 4px;
        }
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
    <pre id="out"></pre>
    <script>
      // ~10,000 elements, like a board with a few hundred cards.
      const root = document.getElementById("root");
      for (let i = 0; i < 1000; i++) {
        const c = document.createElement("div");
        c.className = "card";
        c.innerHTML =
          '<div class="row"><b>Name ' +
          i +
          '</b><span class="muted">#' +
          i +
          "</span></div>" +
          '<p class="muted">123 Main St</p><div class="row"><span>3d</span><span>AB</span><span>x</span><span>y</span></div>';
        root.appendChild(c);
      }
      // A forced style and layout right after inserting one small <style>.
      function time(css, prepend) {
        document.body.offsetHeight;
        const s = document.createElement("style");
        s.textContent = css;
        const t0 = performance.now();
        if (prepend) document.head.prepend(s);
        else document.head.append(s);
        document.body.offsetHeight;
        const ms = performance.now() - t0;
        s.remove();
        document.body.offsetHeight;
        return ms;
      }
      const layered = "@layer dnd-kit { :where([data-dnd-dragging][popover]) { margin: unset; } }";
      const plain = "[data-dnd-dragging] { position: fixed; }";
      const cases = [
        ["layered, prepended", layered, true],
        ["layered, appended", layered, false],
        ["plain, prepended", plain, true],
      ];
      const lines = [];
      for (const [name, css, prepend] of cases) {
        const runs = [];
        for (let i = 0; i < 9; i++) runs.push(time(css, prepend));
        runs.sort((a, b) => a - b);
        lines.push(name.padEnd(20) + " median " + runs[4].toFixed(1) + " ms");
      }
      document.getElementById("out").textContent = lines.join("\n");
    </script>
  </body>
</html>

Measurements

The standalone page (Chromium 158.0.8127.18, median of 9):

Inserted <style> Forced style + layout
@layer dnd-kit {…}, prepended (what StyleInjector does) 21.3 ms
the same, appended 1.0 ms
a plain rule (no @layer), prepended 0.9 ms

A real app page (a board with ~9,600 elements, Tailwind v4 with 57 @property rules):

  • One <style> inserted, then a forced restyle and layout (median): the Feedback rules prepended took 61.7 ms; a one-rule @layer sheet prepended 60.9 ms; the same sheet appended 3.5 ms.
  • Chrome's invalidation tracking at drag start: whole-document style recalculations (9,596 elements), with "PropertyRegistration" and "Fonts changed" (a full layout) as reasons.
  • Drag start to visual feedback (median / slowest, 30 drags, a fresh page each time, Chromium):
    • @dnd-kit/dom 0.5.3 as published: 98 / 101 ms;
    • with prepend changed to append, and the page declaring @layer dnd-kit; before its own layers so the layer keeps the lowest priority: 65 / 82 ms.

Declaring @layer dnd-kit; first in the page's own CSS is not enough while the sheet is prepended: the rebuild still happens (measured: 59.5–60.5 ms).

Suggested change

In StyleInjector's document path, append instead of prepend:

-  root.head.prepend(style);
+  root.head.append(style);
   const observer = new MutationObserver((entries) => {
     for (const entry of entries) {
       for (const node of Array.from(entry.removedNodes)) {
         if (node === style) {
-          root.head.prepend(style);
+          root.head.append(style);

Keeping the lowest priority (the reason #1903 prepends it): a layer's position is fixed by the first place its name appears, not by where the sheet sits in <head>. Appended, dnd-kit would become the last (highest-priority) layer unless the page names it earlier. Options for the library:

  1. Document it: apps that want dnd-kit's layer lowest declare @layer dnd-kit; at the top of their stylesheet (what we did); or
  2. Insert once, early: inject a tiny <style>@layer dnd-kit;</style> when the manager is created (before anything is dragged; it costs nothing while the page is being set up), then append the rules at drag time; or
  3. Use adoptedStyleSheets for documents too, as StyleInjector already does for shadow roots, with the layer ordered the same way.

The universal rules of Cursor (* { cursor: grabbing !important; }) and PreventSelection (* { user-select: none !important; }) also restyle every element at each drag start (no rebuild of the layer order, but a full style recalculation, ~35–40 ms on the same page). A scoping option (for example, a root element) would let apps limit them.

Dominant language
TypeScript
Stars
17.8k
Forks
934
Avg merge
1d 4h
Merged PRs (30d)
7

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from clauderic/dnd-kit

All issues in clauderic/dnd-kit

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.