Prevent FOUC with production links in ViewTransitions (#7756)

* Prevent FOUC with production links in ViewTransitions

* Adding changeset

* Move up so it works with fallback too
This commit is contained in:
Matthew Phillips 2023-07-21 16:26:42 -04:00 committed by GitHub
parent f79ab0bdb3
commit 274e675328
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 43 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fixes case where there is FOUC caused by stylesheets not loaded

View file

@ -47,6 +47,16 @@ const { fallback = 'animate' } = Astro.props as Props;
doc.documentElement.dataset.astroTransition = dir; doc.documentElement.dataset.astroTransition = dir;
const swap = () => document.documentElement.replaceWith(doc.documentElement); const swap = () => document.documentElement.replaceWith(doc.documentElement);
// Wait on links to finish, to prevent FOUC
const links = Array.from(doc.querySelectorAll('head link[rel=stylesheet]')).map(link => new Promise(resolve => {
const c = link.cloneNode();
['load', 'error'].forEach(evName => c.addEventListener(evName, resolve));
document.head.append(c);
}));
if(links.length) {
await Promise.all(links);
}
if (fallback === 'animate') { if (fallback === 'animate') {
let isAnimating = false; let isAnimating = false;
addEventListener('animationstart', () => (isAnimating = true), { once: true }); addEventListener('animationstart', () => (isAnimating = true), { once: true });

View file

@ -0,0 +1,3 @@
#two {
font-size: 24px;
}

View file

@ -1,9 +1,16 @@
--- ---
import { ViewTransitions } from 'astro:transitions'; import { ViewTransitions } from 'astro:transitions';
interface Props {
link?: string;
}
const { link } = Astro.props as Props;
--- ---
<html> <html>
<head> <head>
<title>Testing</title> <title>Testing</title>
{link ? <link rel="stylesheet" href={link} > : ''}
<ViewTransitions /> <ViewTransitions />
</head> </head>
<body> <body>

View file

@ -1,6 +1,6 @@
--- ---
import Layout from '../components/Layout.astro'; import Layout from '../components/Layout.astro';
--- ---
<Layout> <Layout link="/two.css">
<p id="two">Page 2</p> <p id="two">Page 2</p>
</Layout> </Layout>

View file

@ -126,4 +126,21 @@ test.describe('View Transitions', () => {
p = page.locator('#one'); p = page.locator('#one');
await expect(p, 'should have content').toHaveText('Page 1'); await expect(p, 'should have content').toHaveText('Page 1');
}); });
test('Stylesheets in the head are waited on', async ({ page, astro }) => {
page.addListener('console', data => {
console.log(data)
})
// Go to page 1
await page.goto(astro.resolveUrl('/one'));
let p = page.locator('#one');
await expect(p, 'should have content').toHaveText('Page 1');
// Go to page 2
await page.click('#click-two');
p = page.locator('#two');
await expect(p, 'should have content').toHaveText('Page 2');
await expect(p, 'imported CSS updated').toHaveCSS('font-size', '24px');
});
}); });