If you’re using webpack to bundle your application, then you can use webpack magic comments to have webpack instruct the browser to prefetch dynamic imports.
<label onMouseEnter={loadOnDemand} onFocus={loadOnDemand} >
// our element
</label>
Next.js
Next.js supports ES2020 dynamic import() for JavaScript. With it, you can import JavaScript modules dynamically and work with them. They also work with SSR.
// remove this import
import { javascript } from "@codemirror/lang-javascript"
// add this where needed access to {javascript}
const javascript = (await import("@codemirror/lang-javascript")).javascript;
Dynamically import the Hello component with loading component:
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello'),
{ loading: () => <p>...</p> }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
With no server-side rendering:
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
Lazy Loading components with React-Loadable
React-Loadable - a higher-order component for dynamically loading a module before rendering it, a loading component is rendered while the module is unavailable.