Skip to content

Commit

Permalink
Append styles imported in JS to end of document.head
Browse files Browse the repository at this point in the history
This addresses the issue raised in #1033 ("2. Import app.scss from app.js") that link tags added through imports of CSS in JS get added next to the script entrypoint (at the body's end) rather than to the document's head, causing a FOUC in FastBoot rendered pages.
  • Loading branch information
simonihmig committed Dec 10, 2021
1 parent 8182d45 commit c781808
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions packages/core/src/html-placeholder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,14 @@ export default class Placeholder {
}
}

insert(node: Node) {
insert(node: Node): void {
this.end.parentElement.insertBefore(node, this.end);
}

appendToHead(node: Node): void {
this.end.ownerDocument.head.appendChild(node);
}

isScript(): boolean {
return this.target.tagName === 'SCRIPT';
}
Expand Down Expand Up @@ -70,12 +74,20 @@ export default class Placeholder {
let newTag = this.end.ownerDocument.createElement('link');
newTag.href = href;
newTag.rel = 'stylesheet';
this.insert(newTag);
this.insertNewline();

if (this.isScript()) {
// Add dynamic styles from scripts to the bottom of the head, and not to where the script was,
// to prevent FOUC when pre-rendering (FastBoot)
this.appendToHead(newTag);
} else {
// Keep the new style in the same place as the original one
this.insert(newTag);
}
this.insertNewline(newTag as InDOMNode);
}

insertNewline() {
this.end.parentElement.insertBefore(this.end.ownerDocument.createTextNode('\n'), this.end);
insertNewline(node: InDOMNode = this.end): void {
node.parentElement.insertBefore(node.ownerDocument.createTextNode('\n'), node);
}
}

Expand Down

0 comments on commit c781808

Please sign in to comment.