Loading js chunks dynamically / conditionally


Hello, new to Hubspot CMS. I'm looking for a way to dynamically load webpack chunks. My current use case is loading analytics code only if the user accepts tracking.


The chunks are placed in the correct directory and uploaded to Hubspot CMS. I can see them in the /design-manager, but when checking their dependands it says they are not in use anywhere on the site.

Screenshot 2021-09-09 at 09.45.29.png

After accepting tracking the browser will attempt to load the chunk, the URL structure looks correct, but it returns 404 (in browser and with curl).

The exact message displayed in the browser is:

{"message":"File not found 1","status":403}


If I require (require_js tag) the chunk from a component or template it will load, but there are two issues with this approach:

- I have to hard code the chunk name, which is generated by webpack

- the chunk will load as soon as the componenent or template is loaded, no conditional load

If I remove the require tag, the chunk is still available on the same URL, but the browser will try to load it from a different one and fail.

Chunk still here:


Browsers tries to load (IDs are different):



Any help is greatly appreciated, thanks!

2 Replies 2
Guide | Diamond Partner

Hi @dzen , 

What is it that you are trying to achieve? You can set a few parameters in your require_js tag as described in the docs.
You can pass it a string as a second parameter to indicate if you want to load it in the head or in the footer, and you can also pass it a parameter to tell the function if it should load the scrypt async or defer the script:

{{ require_js("http://example.com/path/to/footer-file.js", "footer") }}
{{ require_js("http://example.com/path/to/head-file.js", "head") }}

<!-- you can add async or defer attributes to the tags that are added. -->
{{ require_js(get_asset_url('./path/to/file.js'), { position: 'footer', async: true }) }}
{{ require_js(get_asset_url('./jquery-latest.js'), { position: 'footer', defer:true }) }}
Did my answer solve your issue? Help the community by marking it as the solution.

Hi @Teun , thank you for the quick reply.


I'd like to load custom "analytics.js" only if the user accepts tracking. If I include "analytics.js" in any way using the require_js tag it will always load, regardless of UI interactions.


If I don't require "analytics.js" and initiate the dynamic script load by accepting tracking the URL to "analytics.js" will be incorrect and it fails to load.


Additionally, "analytics.js" code is processed by webpack into a chunk with a random ID and hash (chunk.358.63876d94.js). I can't rely on hard coding this in the template to get it to load because the file name will be different when deployed from another machine.