Create a Router

How can I use a router?

Add the contents of the <head> tag that you want to run globally in your index file. The same goes for <script> tags that will run globally.

If you want to run the <head> tag content and <script> tags only when the page is active, you should use it as shown in the examples below.

What should be considered when using a router?

<a>: If a route is wanted to be activated without refreshing the page, it is required to use the target="_self" attribute.

<router-root>: The data-root attribute is required for the router-root component. You should remove the domain and add the directory as attribute.

<router-page>: The data-path and data-src attributes is required for the router-page component. You must specify which url to listen to in the data-path attribute and which file to run in the data-src attribute.

Simple usage examples

Below are simple examples of how you can use it.

/project/index.html

<!DOCTYPE html>
<html lang="en">

<!-- Global head content -->
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    
    <!-- Global layout -->
    <nav>
        <a href="./" target="_self">Home</a>
        <a href="./about" target="_self">About</a>
    </nav>

    <!-- Routed area & Routing configs -->
    <router-root data-root="/project/">
        <router-page data-path="*" data-src="pages/404.html" />
        <router-page data-path="./" data-src="pages/home.html" />
        <router-page data-path="./about" data-src="pages/about.html" />
    </router-root>

    <!-- Global Javascript -->
    <script src="./src/router.js"></script>
</body>
</html>

/project/pages/home.html

<!-- The <head> tag content that will only be executed if the route is active -->
<head>
    <title>Home | Router</title>
</head>

<!-- Using the <div> tag as shown in the example is not mandatory. Any tag can be used. -->
<!-- All content, excluding <head> and <script> tags, will be considered valid for the new page. -->
<div>
    Home page content
</div>

<!-- The <script> tag that will only be executed if the route is active -->
<script src="./src/home.js">

/project/pages/about.html

<head>
    <title>About | Router</title>
</head>
                
<div>
    About page content
</div>
                
<script src="./src/about.js">

/project/pages/404.html

<head>
    <title>Page not found | Router</title>
</head>
                
<div>
    404 page content
</div>