Chunks not loading when script tag is added dynamically using JS instead of adding it to HTML directly

28 views Asked by At

I have a react app bundled dist/ folder which is hosted on some url (http://localhost:8000). This dist folder comprises of main.js vendor.js which is a chunk for node_modules app.[fullhash].js JS Chunk of component called App app.[fullhash].css CSS Chunk of component called App

Now I have created other react app in which I want to use this code.

When I use

<script src="http://localhost:8000/vendors.js" type="text/javascript" async></script>
<script src="http://localhost:8000/main.js" type="text/javascript" async></script>

the above part of code directly in my index.html file, It is automatically loading respective chunks(app.[fullhash].js, app.[fullhash].css) also. Which is what I wanted.

But I want to add the script dynamically using Javascript instead of adding it in HTML file.

So I used

const scriptElVendors = document.createElement('script');
scriptElVendors.src = 'http://localhost:8000/vendors.js'
scriptElVendors.type = 'text/javascript';
scriptElVendors.async = true;
document.head.appendChild(scriptElVendors);

const scriptElMain = document.createElement('script');
scriptElMain.src = 'http://localhost:8000/main.js'
scriptElMain.type = 'text/javascript';
scriptElMain.async = true;
document.head.appendChild(scriptElMain);

When I use this, It is only fetching main.js and vendors.js but not the respective chunks.

I want to add script tags dynamically using JS. And also it should automatically fetch the chunks also.

Can anyone help me solve this?

I tried using relative import from local filesystem and also from the server. In both of these, Adding script dynamically using JS didn't fetch respective chunks.

0

There are 0 answers