Next.js中CSS与JS重复渲染问题求助
Hey there, I’ve run into similar resource loading quirks with older Next.js versions—let’s break down how to fix this duplicate preload/regular load issue you’re seeing.
Possible Causes & Solutions
1. Check Your Custom _document.js
If you’ve customized the root _document.js file, it’s easy to accidentally duplicate resource references. Next.js automatically injects CSS/JS bundles via the <NextScript /> component and its internal SSR logic—manual additions here will cause duplicates.
Make sure your _document.js follows the standard structure without extra <link> or <script> tags for Next-generated assets:
import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps }; } render() { return ( <Html> <Head> {/* Only add custom external resources here (like favicons, fonts) */} <link rel="icon" href="/favicon.ico" /> </Head> <body> <Main /> {/* Let Next.js handle script injection */} <NextScript /> </body> </Html> ); } } export default MyDocument;
2. Upgrade Next.js to a Stable Patch Version
Next.js 9.2.x had several known bugs around resource preloading and SSR asset injection—9.2.1 specifically has issues where preloaded assets get re-requested as regular loads.
Upgrade to 9.4.4 (a stable patch that fixes these quirks while staying compatible with your Node 12.x and React 16.12.x setup):
npm install next@9.4.4 # Or for Yarn users: yarn add next@9.4.4
3. Clear Build & Node Cache
Stale cached files from previous builds can cause duplicate asset references. Clean up these directories and rebuild:
# Delete Next.js build cache rm -rf .next/ # Delete Node module cache rm -rf node_modules/.cache/ # Rebuild your app npm run build
4. Audit Custom Webpack Configs & Third-Party Libraries
If you’ve modified next.config.js with custom webpack rules, ensure you aren’t adding redundant CSS/JS loaders (Next.js handles these internally). For example, avoid manually adding style-loader or css-loader unless absolutely necessary.
If you’re using CSS-in-JS libraries like styled-components, double-check that you’ve configured them correctly in _document.js to avoid duplicate style injection.
How to Verify the Fix
After applying these steps:
- Open your browser’s Network tab and filter by JS/CSS
- Confirm each asset is only loaded once (either preloaded then used, or loaded normally—no duplicate requests)
- Check the server-rendered HTML source to ensure no duplicate
<link rel="preload">or<script>tags for the same asset
内容的提问来源于stack exchange,提问作者Jashanpreet Singh

