Optimizing Fonts & Scripts
Next.js includes built-in loaders for optimizing third-party fonts and scripts, ensuring fast initial page loads and improving Core Web Vitals.
1 next/font loading styles and next/script parameters
Key features for managing fonts and scripts include:
- next/font: Self-hosts Google Fonts locally during the build process. This prevents layout shifts and blocks external network requests for font assets, improving privacy and speed.
- next/script: Optimizes loading strategies for third-party scripts (e.g. Google Analytics). Use the
strategyattribute to control load timing (e.g.beforeInteractive,afterInteractive,lazyOnload).
2 Fonts and Scripts Implementation
Let's check how to import and apply an optimized font:
React — Font and Script Loading
import { Inter } from 'next/font/google';
import Script from 'next/script';
// Configure font parameters
const inter = Inter({
subsets: ['latin'],
display: 'swap'
});
export default function Layout({ children }) {
return (
<div className={inter.className}>
<!-- Load analytics script lazily -->
<Script
src="https://example.com/analytics.js"
strategy="lazyOnload"
onLoad={() => console.log('Analytics loaded successfully.')}
/>
{{ children }}
</div>
);
}
3 Code Challenge
Challenge: Configure a Google Font with custom weight parameters (e.g.
'400', '700') using the next/font/google loader, and apply it to a heading element.