Skip to content

Commit

Permalink
Cherry pick create style element fix (#25387)
Browse files Browse the repository at this point in the history
* Add some logic to stylesheet that will do a simple append instead of using insert before if the reference node isn't actually a child of the document head.

* Change files
  • Loading branch information
GeoffCoxMSFT authored Oct 28, 2022
1 parent 76952a3 commit 3727ad3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Add some logic to stylesheet that will do a simple append instead of using insert before if the reference node isn't actually a child of the document head.",
"packageName": "@uifabric/merge-styles",
"email": "gcox@microsoft.com",
"dependentChangeType": "patch"
}
9 changes: 6 additions & 3 deletions packages/merge-styles/src/Stylesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ export class Stylesheet {
private _createStyleElement(): HTMLStyleElement {
const head: HTMLHeadElement = document.head;
const styleElement = document.createElement('style');
let nodeToInsertBefore: Node | null = null;

styleElement.setAttribute('data-merge-styles', 'true');

Expand All @@ -315,16 +316,18 @@ export class Stylesheet {
if (this._lastStyleElement) {
// If the `nextElementSibling` is null, then the insertBefore will act as a regular append.
// https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore#Syntax
head!.insertBefore(styleElement, this._lastStyleElement.nextElementSibling);
nodeToInsertBefore = this._lastStyleElement.nextElementSibling;
} else {
const placeholderStyleTag: Element | null = this._findPlaceholderStyleTag();

if (placeholderStyleTag) {
head!.insertBefore(styleElement, placeholderStyleTag.nextElementSibling);
nodeToInsertBefore = placeholderStyleTag.nextElementSibling;
} else {
head!.insertBefore(styleElement, head.childNodes[0]);
nodeToInsertBefore = head.childNodes[0];
}
}

head!.insertBefore(styleElement, head!.contains(nodeToInsertBefore) ? nodeToInsertBefore : null);
this._lastStyleElement = styleElement;

return styleElement;
Expand Down

0 comments on commit 3727ad3

Please sign in to comment.