Route pages in the browser without reloading
jComponent has its own router for single page applications. ROUTE(url, fn) registers a route: {name} segments are passed to fn as arguments in order. REDIRECT(url) changes the address with the History API (no page load) and runs the route that matches. Routes are compared segment by segment: a route and a URL must have the same number of segments, and * matches any value at its position. NAV describes the current location: NAV.url is the path, NAV.query the parsed query string and NAV.params the route arguments. NAV.back() and NAV.forward() move through the history that jComponent keeps.
For the server this is still one page, so every URL below your app has to return the same HTML (a ROUTE('GET /*') that renders the shell), otherwise a reload on /users/5/ would give a 404.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jComponent</title>
<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
<h1 id="title"></h1>
<script>
ROUTE('/', function() {
$('#title').text('Home');
});
ROUTE('/users/{id}/', function(id) {
$('#title').text('User ' + id);
});
ROUTE('/files/*', function() {
$('#title').text('Files');
});
</script>
</body>
</html>Edit the example and run it. It runs in an isolated frame in your browser; nothing is sent to our server.
Preview