Created
October 18, 2020 18:14
-
-
Save alfonmga/af1c8ac2af8cf845f777ba68f4eeab7c to your computer and use it in GitHub Desktop.
Next.js lazy load / preload CSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NextHead from 'next/head' | |
import { useEffect, useRef, useState } from 'react' | |
export type LazyLoadCSSProps = { | |
href: string | |
} | |
let hydrated = false | |
const LazyLoadCSS: React.FC<LazyLoadCSSProps> = ({ href }) => { | |
const hydratedRef = useRef(false) | |
const [, rerender] = useState(false) | |
useEffect(() => { | |
if (!hydratedRef.current) { | |
hydrated = true | |
hydratedRef.current = true | |
rerender(true) | |
} | |
}, []) | |
return ( | |
<NextHead> | |
<link rel="preconnect" href={href} /> | |
<link rel="preload" as="style" href={href} /> | |
<link href={href} rel="stylesheet" media={!hydrated ? 'print' : 'all'} /> | |
</NextHead> | |
) | |
} | |
export default LazyLoadCSS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment