Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Prevent FOUC in the iframe while loading (#339)
Vite 2.9+ exhibit a flash of unstyled content in the head while the page loads in. This approach adds some styles from https://github.com/yannbf/mealdrop/blob/feat/lazy-compilation/.storybook/preview-head.html into the head, after vite has finished processing. This is necessary (instead of just putting the styles in the iframe html) due to vitejs/vite#6737. With the changes here, we no longer see content like this: ![image](https://user-images.githubusercontent.com/4616705/163624147-70c78cd9-4784-43b3-b2e6-b848fc3f6582.png)
- Loading branch information
Showing
3 changed files
with
51 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import type { Plugin } from 'vite'; | ||
|
||
/** | ||
* This plugin is a workaround to inject some styles into the `<head>` of the iframe to | ||
* prevent the "no story" text from appearing breifly while the page loads in. | ||
* | ||
* It can be removed, and these styles placed back into the head, | ||
* when https://github.com/vitejs/vite/issues/6737 is closed. | ||
*/ | ||
export function noFouc(): Plugin { | ||
return { | ||
name: 'no-fouc', | ||
enforce: 'post', | ||
async transformIndexHtml(html, ctx) { | ||
if (ctx.path !== '/iframe.html') { | ||
return; | ||
} | ||
|
||
return insertHeadStyles(html); | ||
}, | ||
}; | ||
} | ||
|
||
function insertHeadStyles(html: string) { | ||
return html.replace( | ||
'</head>', | ||
` | ||
<style> | ||
/* Fix for elements flashing */ | ||
body > * { | ||
display: none !important; | ||
} | ||
.sb-show-preparing-story > .sb-preparing-story, | ||
.sb-show-preparing-docs > .sb-preparing-docs, | ||
.sb-show-nopreview > .sb-nopreview, | ||
.sb-show-errordisplay > .sb-errordisplay, | ||
.sb-show-main > #root, | ||
.sb-show-main > #docs-root { | ||
display: block !important; | ||
} | ||
#root[hidden], | ||
#docs-root[hidden] { | ||
display: none !important; | ||
} | ||
</style> | ||
</head> | ||
`.trim() | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters