Search code examples
htmlreactjsoptimization

Optimize multiple react apps loaded around iframe


Context :

I have HTML page, this page load 2 different React apps using iframe =>

<html>
   <iframe src="<served-app-1.html"/>
   <iframe src="<served-app-2.html"/>
   <iframe src="<served-app-3.html"/>
</html>

But I assume that the two applications use some of the same bundle code (as react core) ?

If yes, there is a way to share this part of code one time ?


Solution

  • My solution is to load the lib, I used preact instead of react but it's probably the same solution.

    On iframe app, in bundler you used (webpack, vite, ...)

    vite.config.ts

    import { defineConfig } from "vite";
    import createExternal from "vite-plugin-external";
    
    export default defineConfig({
      plugins: [
        createExternal({
          externals: {
            react: "Preact",
          },
        }),
      ],
    });
    

    and in the parent html page :

    <html>
      <head>
        <script src="https://unpkg.com/preact@10.15.1/dist/preact.min.js"></script>
      </head>
      <body>
        <iframe src="<served-app-1.html"/>
        <iframe src="<served-app-2.html"/>
        <iframe src="<served-app-3.html"/>
      </body>
    </html>
    

    on each served-app index.html, add this tag in head

    <script>
      window.onload = () => {
        window.preact = window.parent.preact
        console.log("preact loaded from parent window")
      }
    </script>