Skip to content

fix: avoid FOUC and deduplication optimization in style-loader insert (dev)#321

Open
Antamansid wants to merge 1 commit into
gravity-ui:mainfrom
Antamansid:fix_fouc_in_ff
Open

fix: avoid FOUC and deduplication optimization in style-loader insert (dev)#321
Antamansid wants to merge 1 commit into
gravity-ui:mainfrom
Antamansid:fix_fouc_in_ff

Conversation

@Antamansid
Copy link
Copy Markdown

@Antamansid Antamansid commented May 21, 2026

Problem

The custom insert for style-loader (dev only) deduped <style> tags by comparing innerHTML against every existing tag on each insertion — O(n²) over tag count. With ~500 style files this is ~128k full-string comparisons.

It also deferred insertion via setTimeout (a macrotask), so the browser could paint the unstyled DOM before styles applied. This produced a visible flash of unstyled content (FOUC) in Firefox; Chrome happened not to show it.

Fix

  • Defer with queueMicrotask instead of setTimeout. Microtasks drain at the end of the current task, before the browser paints, so styles apply without a flash. The deferral is still required because style-loader passes an empty <style> element and fills its content only after insert returns.
  • Replace the O(n²) innerHTML scan with an O(n) lookup: store a content hash in a data-ab-styleid attribute and find duplicates via querySelector. The attribute lives on the tag, so it reflects DOM removals (HMR) automatically. A final innerHTML equality check guards against the rare hash collision, keeping dedup behavior identical.

Dev-only change; production uses MiniCssExtractPlugin and is unaffected.

Copy link
Copy Markdown
Contributor

@DakEnviy DakEnviy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great optimization, thank you! Actually, it's O(n) now against O(n^2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants