Skip to content

Commit

Permalink
perf: don't lock main thread when adding / removing styles
Browse files Browse the repository at this point in the history
setTimeout(fn, 0) tells JS to wait until the current thread is finished
  • Loading branch information
chrisvxd committed Apr 11, 2024
1 parent 8630d97 commit f62f5e8
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/AutoFrameComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ const getStyles = (styleSheet?: CSSStyleSheet) => {
return "";
};

const defer = (fn: () => void) => setTimeout(fn, 0);

const CopyHostStyles = ({
children,
debug = false,
Expand Down Expand Up @@ -162,7 +164,7 @@ const CopyHostStyles = ({
: (node as HTMLElement);

if (el && el.matches(styleSelector)) {
addEl(el);
defer(() => addEl(el));
}
}
});
Expand All @@ -178,7 +180,7 @@ const CopyHostStyles = ({
: (node as HTMLElement);

if (el && el.matches(styleSelector)) {
removeEl(el);
defer(() => removeEl(el));
}
}
});
Expand All @@ -193,13 +195,15 @@ const CopyHostStyles = ({
let mountedCounter = 0;

collectedStyles.forEach((styleNode) => {
addEl(styleNode as HTMLElement, () => {
mountedCounter += 1;
defer(() =>
addEl(styleNode as HTMLElement, () => {
mountedCounter += 1;

if (mountedCounter === collectedStyles.length) {
onStylesLoaded();
}
});
if (mountedCounter === collectedStyles.length) {
onStylesLoaded();
}
})
);
});

observer.observe(parentDocument.head, { childList: true, subtree: true });
Expand Down

0 comments on commit f62f5e8

Please sign in to comment.