Skip to content

FOUC creates unreliable JS style calculations on page load #293

Closed
@t-kelly

Description

@t-kelly

FOUC in a development environment isn't really a problem
@michael-ciniawsky in #221 (comment)

Related

Style-loader uses a <link> to include styles when sourcemaps are enabled. Since injecting a <link> tag into the page via JS, after page-load, results in the the stylesheet being downloaded asynchronously, other JS has time to execute before that stylesheet is downloaded and applied to the page.

The resulting FOUC causes problems when JS needs to read styles from the DOM and is expecting a fully styled page. For example, let's say you have the following page built for production, that uses HTMLWebpackPlugin to inline a <link> tag at build-time.

styles.css

header {
  height: 100px
}

index.html

<html>
<head>
  ...
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <header id="header"> My header </header>
  ...
  <script>
    console.log(document.getElementById("header").styles.height);
  </script>
</body>

The height logged will always be 100px because a <link> tag that is included on page load is synchronous and render-blocking.

The same page when using style-loader with source-maps will always end up with another value (the unstyled page value) because the JS executes before the stylesheet has loaded.

The unreliability produces big problems for features like sticky elements in development, which need access to the styled page values to function correctly.

This problem is identical to those encountered when working with asynchronous stylesheets, e.g. using a lib like LoadCSS. One solution would be to check if the stylesheet has loaded before executing the JS, but that kind of sucks since this problem only exists in dev.

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