From 95a957ef48f60a55692cadc0e5d9fc55cb6f8b28 Mon Sep 17 00:00:00 2001 From: Chris Meagher Date: Wed, 15 Nov 2023 21:22:47 +0000 Subject: [PATCH] Add preconnect for CDN resources --- src/app/layout.tsx | 2 ++ src/app/preload-resources.tsx | 17 +++++++++++++++++ src/lib/url.ts | 16 ++++++++++++---- 3 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 src/app/preload-resources.tsx diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 5d33957..d432d44 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,6 +1,7 @@ import './globals.css' import type { Metadata } from 'next' import { Inter } from 'next/font/google' +import { PreloadResources } from './preload-resources' import { AppInsightsProvider } from '@/components/instrumentation/AppInsightsProvider' const inter = Inter({ subsets: ['latin'] }) @@ -17,6 +18,7 @@ export default function RootLayout({ }) { return ( + {children} diff --git a/src/app/preload-resources.tsx b/src/app/preload-resources.tsx new file mode 100644 index 0000000..c088752 --- /dev/null +++ b/src/app/preload-resources.tsx @@ -0,0 +1,17 @@ +'use client' + +import ReactDOM from 'react-dom' +import { getCdnUrl } from '@/lib/url' + +function PreloadResources() { + const cdnUrl = getCdnUrl('', false) + + if (cdnUrl.length > 0) { + // @ts-ignore + ReactDOM.preconnect(cdnUrl) + } + + return null +} + +export { PreloadResources } diff --git a/src/lib/url.ts b/src/lib/url.ts index 81cfd67..b13d3ae 100644 --- a/src/lib/url.ts +++ b/src/lib/url.ts @@ -32,12 +32,20 @@ const getAbsoluteUrl = (path?: string) => { return joinUrlSegments([baseUrl, path]) } -const getCdnUrl = (path: string) => { - if (!baseCdnUrl || !buildId) { - return path +const getCdnUrl = (path?: string, includeFingerprint = true) => { + if (!baseCdnUrl) { + return path ?? '' } - return joinUrlSegments([baseCdnUrl, buildId, path]) + if (!path) { + return baseCdnUrl + } + + if (includeFingerprint && buildId) { + return joinUrlSegments([baseCdnUrl, buildId, path]) + } + + return joinUrlSegments([baseCdnUrl, path]) } export { getAbsoluteUrl, getCdnUrl }