Skip to content

Instantly share code, notes, and snippets.

@emersonlaurentino
Created October 9, 2020 15:05
Show Gist options
  • Save emersonlaurentino/689119ea1b7c5ceb1e7469f762ada4a1 to your computer and use it in GitHub Desktop.
Save emersonlaurentino/689119ea1b7c5ceb1e7469f762ada4a1 to your computer and use it in GitHub Desktop.
Lazy Scripts
import React, { FC, lazy, Suspense, useEffect, useState } from 'react'
const preloadComponent = () => import('./Component')
const Component = lazy(preloadDrawer)
const App: FC = () => {
useEffect(() => {
const handler = window.requestIdleCallback(preloadComponent)
return () => window.cancelIdleCallback(handler)
}, [])
return (
<Suspense fallback={() => <div>Loading...</div>}>
<Component />
</Suspense>
)
}
export default App
import React from 'react'
import { GatsbySSR } from 'gatsby'
export const onRenderBody: GatsbySSR = ({ setPostBodyComponents }) => {
setPostBodyComponents([
React.createElement('script', {
type: 'application/javascript',
dangerouslySetInnerHTML: {
__html: stripIndent`
(function () {
function registerScript () {
YOUR_SCRIPT
}
if (document.readyState === 'complete') {
window.requestIdleCallback(registerScript);
} else {
window.addEventListener("load", registerScript);
}
})();
`,
},
}),
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment