April 20, 2021 by @Austin Pray

<aside> 💡 Draft of a blog post for the roots.io blog

</aside>

Sage 6 through alpha versions of 10 included a DOM-based Routing solution based on an idea Paul Irish had in 2009. The DOM-based router was never really a terrible idea or anything, it definitely proved to be a reliable way to control the execution of your scripts from markup generated on the server side. However, in 2021, we now have access to powerful code splitting tools in webpack and natively in the browser which solve the problem in a categorically better way.

Let's explore idea this via example. Let's suppose we have an "about us" page that requires a small gallery script to show off our executive staff.

A gallery script on your about page

A gallery script on your about page

DOM-based routing is not a good design

Let's assume our about page has a slug as about-us. In our theme we stick this slug in a class on the body.

<body class="about-us">

The about us page contains some gallery markup that is made interactive by our javascript bundle.

<div class="fancy-gallery">
	<figure>
		<img src="yui.jpg" alt="cute yui!!">
		<h3>Yui</h3>
		<p>CEO</p>
	</figure>
	<!-- and so on and so forth... -->
</div>

We know our DOM router will attempt to fire a route named aboutUs based on this about-us class. So we create an aboutUs route in our DOM router that does all the necessary work to kick off the small gallery script targeting the .fancy-gallery element that we know lives the about us page.

We add our  route.

We add our aboutUs route.

This code maps the  slug to the JS  name.

This code maps the about-us slug to the JS aboutUs name.

Everything works, but we are left with a javascript bundle that his highly coupled to the server-side markup generation. Furthermore, the javascript bundle is highly coupled to the expected content of the page. All our effort and coordination essentially amounts to the following pseudocode:

if we are on the "about us" page:
	initialize our gallery on the .fancy-gallery element

Wait a minute. Why is the fact that we are on the about us page relevant at all? Why not just check for the element's existence in the first place?

if the .fancy-gallery element exists:
	initialize our gallery on the .fancy-gallery element

Now the .fancy-gallery component is decoupled from any knowledge of what page it lives on. Let's compare the work involved in fulfilling changing requirements that come down the pipe.

We want a fancy gallery on the contact page as well

DOM-router: Add a contact page route in the javascript bundle that kicks off the fancy gallery. Rebuild and redeploy.

Element existence check: Nothing, just add the gallery markup to that page.