React.lazy and prefetching components

前端 未结 1 1754
梦毁少年i
梦毁少年i 2021-01-03 16:57

I have a 2 step Application Flow that looks like this:

const Step1 = React.lazy(() => import(\'./Step1\'));
const Step1 = React.lazy(() => import(\'./S         


        
相关标签:
1条回答
  • 2021-01-03 17:31

    I was also reading about this few days back and I liked this approach:

    Enhance the React.lazy to have a callback that can be used to load the component. Something like this:

    function lazyWithPreload(factory) {
      const Component = React.lazy(factory);
      Component.preload = factory;
      return Component;
    }
    
    const ComponentToPreload = lazyWithPreload(() => import("./Component"));
    
    /* usage in Component */
    
    ComponentToPreload.preload(); // this will trigger network request to load the component
    
    
    

    In this way, you can preload the component wherever you want. Like on click event or after the current component has Mounted.

    Must read the original post: https://medium.com/hackernoon/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d


    If you are using react-loadable. You can check this: https://github.com/jamiebuilds/react-loadable#preloading

    Hope this helps!

    0 讨论(0)
提交回复
热议问题