Search code examples
reactjswebpackcreate-react-app

React Chunk download background


In my react app production build i need a chunk to be downloaded in the browser in background. The issue is that currently when i click a button it will start "await" for an import operation of the module and wait for the browser to have that chunk. Since this module in is a functional module it's not related to any component hence i can't use code splitting.

export const dialog_xlsx_array_create = async (raw, head) => {
  const Excel = await import('exceljs/modern.browser');
  let xlsxarray = [];
<----some operations--->

the above function is only called when i click a button. but this module is almost 1 Mb. I need this module to be downloaded by the browser in background (can't bundle it with main chunk due to size issues)


Solution

  • You should use the webpack magic comment “prefetch” to instruct the browser to download this chunk during idle time:

    import(/* webpackPrefetch: true */ 'exceljs/modern.browser');
    

    This will add a prefetch link to your head tag when your main module including this dynamic import had loaded