Hey @MB-Jan,
To clarify this:
The order of execution for routes is:
- The init scripts in the common route (after the browser’s DOM load event)
- For each route matching the loaded page (e.g., home), the init scripts and then the finalize scripts
- The finalize scripts in the common route
When the custom routes run in step #2, it doesn’t run all of the init scripts from the routes and then all of the finalize scripts from the routes, it runs init and finalize from route 1, then init and finalize from route 2, and so on. In other words, putting something in finalize doesn’t mean that it will run after the init scripts from all custom routes, only that it will run after the init scripts of the route in which you’ve placed it.
When you say you tried changing the route order, I’m assuming you meant the order in which they are listed in the routes
declaration in main.js
?
/** Populate Router instance with DOM routes */
const routes = new Router({
// All pages
common,
// Home page
home,
// About Us page, note the change from about-us to aboutUs.
aboutUs,
});
E.g., to try to change the order, you might have moved aboutUs
before home
.
If that’s what you meant, unfortunately that doesn’t affect the order in which the routes are run.
To find and run the custom routes, the Router.loadEvents()
method gets document.body.className
, which contains a list of the class names on the current page’s body element and then goes through that list one class at a time. This is why your routes have to be named after a body class name. For each class, if there is a matching route, it runs the init scripts and then the finalize scripts, and then it moves on to the next class name. Because of this, the order in which the routes are run is determined by the order of the class names in document.body.className
. I don’t know what, if anything, determines that order.
I’m not sure there’s a way to get it working reliably with two custom routes because of that ordering issue, but if you wanted to avoid using the window’s load event, I would move it to the common route and put it in a conditional that checks if the current page’s body has the class name you are currently using for the custom route where you are attaching the event listener. Note that if you did it that way you’d want to check the actual class name, not the camel case version of the name you use for the route name (e.g., you would check for “front-page” and not “frontPage”).