gpt4 book ai didi

javascript - 如何在 next.js 中延迟加载渲染阻塞 css?

转载 作者:行者123 更新时间:2023-12-03 07:13:10 66 4
gpt4 key购买 nike

正如您在下面的 next.js 代码中看到的那样,我试图通过在 href 属性中提供 main.css 文件路径来延迟加载渲染阻塞 css,但我在 next.js 中努力做到这一点。我想要的是在标签下的_document.js标签中加载关键css后,加载不在首屏的非关键css。
_app.js

import App from "next/app"
import Head from "next/head"
import React from "react"
import { observer, Provider } from 'mobx-react'
import Layout from "../components/Layout"
import allStores from '../store'

export default class MyApp extends App {
componentDidMount = () => {

};
render() {
const { Component, pageProps, header, footer, } = this.props
return (
<>
<Head >
<link rel="preload" href="path/to/main.css" as="style"
onLoad="this.onload=null;this.rel='stylesheet'"></link>
</Head>
<Provider {...allStores}>
<Layout header={header} footer={footer}>
<Component {...pageProps} />
</Layout>
</Provider>
</>
)
}
}

最佳答案

正如@chrishrtmn 在 _document.js 所说,你可以这样做:

import Document, { Main, NextScript } from 'next/document';
import { CriticalCss } from '../components/CriticalCss';

class NextDocument extends Document {
render() {
return (
<html>
<CriticalCssHead />
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}

export default NextDocument;

就像在您的组件中一样,您可以放置​​ CSS:
import { readFileSync } from 'fs';
import { join } from 'path';

export interface Props {
assetPrefix?: string;
file: string;
nonce?: string;
}

export const InlineStyle: React.FC<Props> = ({ assetPrefix, file, nonce }) => {
const cssPath = join(process.cwd(), '.next', file);
const cssSource = readFileSync(cssPath, 'utf-8');
const html = { __html: cssSource };
const id = `${assetPrefix}/_next/${file}`;
return <style dangerouslySetInnerHTML={html} data-href={id} nonce={nonce} />;
};

我从当前的 repo 中得到了这段代码的源代码:
https://github.com/JamieMason/nextjs-typescript-tailwind-critical-css
看看这里
https://github.com/JamieMason/nextjs-typescript-tailwind-critical-css/tree/master/components/CriticalCssHead

关于javascript - 如何在 next.js 中延迟加载渲染阻塞 css?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63223698/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com