Looking for some advice on how to route js to individual pages

Hi all, just looking for some advice regarding routing for JS as I’m coming from Sage9 which had a router built in. I don’t think Sage11 has such a thing in place(?).

Sage9 had ./util/Router.js and ./util/cameCase.js in the assets/scripts/ directory. With this setup I could create a new Page for example “Test Page” and create a new js file - ./routes/testPage.js - then as long as I import the file in ./main.js' and add it to the routes object, it would get loaded on the page automatically and it meant that I only load the javascript I need when I need it. I think this works via the WordPress page class or something.

I know want to replicate something like this in Sage11, I am going to need to target React modules on certain pages, so I don’t want to be loading them on pages that don’t need them. Would I be best to take the utilities (Router.js and camelCase.js) and just add it to Sage11 verbatim or is there a better way?

Thanks in advance.

The old Sage router isn’t relevant with modern JavaScript anymore, take a look into dynamic imports

OK so after a quick look here import() - JavaScript | MDN, are the correct steps something like this…

  1. Parse the current page URL and write a path to a module into a variable e.g pathToModule depending on which URL we are on
  2. Use import(pathToModule).then().catch() on the “DOMContentLoaded” event to load the correct module

Thanks

1 Like