Created
October 9, 2020 15:05
-
-
Save emersonlaurentino/689119ea1b7c5ceb1e7469f762ada4a1 to your computer and use it in GitHub Desktop.
Lazy Scripts
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 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 |
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 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