Skip to content

Commit 9622fe8

Browse files
committed
fix: attempt to preserve space while loading to avoid CLS
1 parent ec10316 commit 9622fe8

6 files changed

Lines changed: 116 additions & 6 deletions

File tree

‎apps/site/components/CarbonAds/TopBar.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import type { FC } from 'react';
77
import styles from './index.module.css';
88

99
const CarbonTopBar: FC = () => {
10-
const { ad, ref } = useCarbonAd('CWBI6KJY');
10+
const { ad, loading, ref } = useCarbonAd('CWBI6KJY');
1111

1212
if (!ad) {
13-
return null;
13+
return loading ? (
14+
<aside aria-hidden="true" className={styles.topBarPlaceholder} />
15+
) : null;
1416
}
1517

1618
return (

‎apps/site/components/CarbonAds/index.module.css‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,21 @@
3434
rounded-md
3535
px-4
3636
py-2
37-
text-sm;
37+
text-sm
38+
lg:min-h-14;
39+
}
40+
41+
/* Matches the banner's minimum height, so that it doesn't shift the page when it loads */
42+
.topBarPlaceholder {
43+
@apply mb-4
44+
hidden
45+
lg:block
46+
lg:h-14;
47+
48+
/* While hidden, it still stops the next heading from matching `first:mt-0` in markdown.css */
49+
& + :is(h1, h2, h3, h4, h5, h6) {
50+
@apply max-lg:mt-0;
51+
}
3852
}
3953

4054
.topBarLink {

‎apps/site/hooks/__tests__/useCarbonAd.test.jsx‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,57 @@ describe('useCarbonAd', () => {
9090
assert.equal(requests[0].searchParams.get('ignore'), 'yes');
9191
});
9292

93+
describe('loading', () => {
94+
const LoadingProbe = () => {
95+
const { ad, loading } = useCarbonAd('CWBI6KJY');
96+
97+
return <div>{`${loading}:${ad?.company}`}</div>;
98+
};
99+
100+
const respondWith = implementation => {
101+
globalThis.fetch.mock.mockImplementation(implementation);
102+
};
103+
104+
it('is true until the ad has loaded', async () => {
105+
const { container } = render(<LoadingProbe />);
106+
107+
assert.equal(container.textContent, 'true:undefined');
108+
109+
await flush();
110+
111+
assert.equal(container.textContent, 'false:Company');
112+
});
113+
114+
it('is false after an empty response', async () => {
115+
respondWith(async () => ({ ok: true, json: async () => ({ ads: [] }) }));
116+
117+
const { container } = render(<LoadingProbe />);
118+
await flush();
119+
120+
assert.equal(container.textContent, 'false:undefined');
121+
});
122+
123+
it('is false after an error response', async () => {
124+
respondWith(async () => ({ ok: false }));
125+
126+
const { container } = render(<LoadingProbe />);
127+
await flush();
128+
129+
assert.equal(container.textContent, 'false:undefined');
130+
});
131+
132+
it('is false after a failed request', async () => {
133+
respondWith(async () => {
134+
throw new TypeError('Failed to fetch');
135+
});
136+
137+
const { container } = render(<LoadingProbe />);
138+
await flush();
139+
140+
assert.equal(container.textContent, 'false:undefined');
141+
});
142+
});
143+
93144
it('sends the view beacon after the ad was at least 50% visible for one second', async t => {
94145
await renderAd(t);
95146

‎apps/site/hooks/useCarbonAd.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export const adColors = (ad: CarbonAd) =>
2727

2828
const useCarbonAd = (zone: string, media?: string) => {
2929
const [ad, setAd] = useState<CarbonAd | null>(null);
30+
const [loading, setLoading] = useState(true);
3031
const ref = useRef<HTMLElement>(null);
3132
// Layouts persist across navigations, so refetch per page
3233
const pathname = usePathname();
@@ -47,11 +48,17 @@ const useCarbonAd = (zone: string, media?: string) => {
4748
fetch(url, { signal: controller.signal })
4849
.then(response => (response.ok ? response.json() : null))
4950
.then(data => data?.ads?.[0]?.statlink && setAd(data.ads[0]))
50-
.catch(() => {});
51+
.catch(() => {})
52+
.finally(() => {
53+
if (!controller.signal.aborted) {
54+
setLoading(false);
55+
}
56+
});
5157

5258
return () => {
5359
controller.abort();
5460
setAd(null);
61+
setLoading(true);
5562
};
5663
}, [zone, matches, pathname]);
5764

@@ -84,7 +91,7 @@ const useCarbonAd = (zone: string, media?: string) => {
8491
};
8592
}, [ad]);
8693

87-
return { ad, ref };
94+
return { ad, loading, ref };
8895
};
8996

9097
export default useCarbonAd;

‎apps/site/tests/e2e/carbon-ads.spec.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,40 @@ test.describe('Carbon Ads', () => {
124124
`/ads/${zones.top}.json`,
125125
]);
126126
});
127+
128+
for (const path of [
129+
'/en/about',
130+
'/en/blog/announcements/diving-into-the-nodejs-website-redesign',
131+
]) {
132+
test(`should not shift ${path} when the Top Bar loads`, async ({
133+
page,
134+
}) => {
135+
await mockAds(page);
136+
137+
let respond = () => {};
138+
const response = new Promise<void>(resolve => (respond = resolve));
139+
140+
await page.route(
141+
`https://srv.carbonads.net/ads/${zones.top}.json*`,
142+
async route => {
143+
await response;
144+
await route.fallback();
145+
}
146+
);
147+
148+
await page.goto(path);
149+
150+
// Only the position matters: the heading's size can change as fonts load
151+
const heading = page.locator('main h1').first();
152+
const before = await heading.boundingBox();
153+
154+
respond();
155+
156+
await expect(adLinks(page)).toHaveCount(2);
157+
158+
const after = await heading.boundingBox();
159+
160+
expect(after?.y).toBe(before?.y);
161+
});
162+
}
127163
});

‎docs/carbon-ads.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Learn (`/learn`) and the API docs (`/api`, `/docs`) are separate applications an
2828
## How it works
2929

3030
- `apps/site/hooks/useCarbonAd.ts` requests the ad for the current page view and sends its view beacon. A page view changes with the pathname or locale (not with hashes or query strings), so a revisited page always gets a fresh ad.
31-
- `apps/site/components/CarbonAds/TopBar.tsx` and `apps/site/components/CarbonAds/Sidebar.tsx` render each format. No space is reserved while loading; when there is no ad (empty response, invalid data, network error or ad blocker) nothing is shown.
31+
- `apps/site/components/CarbonAds/TopBar.tsx` and `apps/site/components/CarbonAds/Sidebar.tsx` render each format. From the `lg` breakpoint, the Top Bar reserves its minimum height while loading, so one- and two-line creatives don't shift the page; longer ones can still shift it slightly. Narrower screens reserve no space, because the height varies too much with the creative's length, and neither does the Sidebar, because it is the last item in its column. When there is no ad (empty response, invalid data, network error or ad blocker) nothing is shown, and any reserved space collapses.
3232
- The ad request itself records the impression. The `statview` beacon is sent once per page view after at least 50% of the ad was visible for one continuous second. Clicks go through `statlink`.
3333

3434
## Staging and production

0 commit comments

Comments
 (0)