Top Related Projects
Micro client-side router inspired by the Express router
A simple vanilla JavaScript router.
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Quick Overview
Crossroads.js is a lightweight JavaScript routing library that helps manage URL fragments and parameters in single-page applications. It provides a flexible and powerful way to handle routing in client-side JavaScript applications, allowing developers to create more organized and maintainable code structures.
Pros
- Lightweight and flexible, with no dependencies
- Supports complex routing patterns, including optional parameters and wildcards
- Easily integrable with other JavaScript libraries and frameworks
- Extensive documentation and examples available
Cons
- Not actively maintained (last commit was in 2016)
- May require additional libraries for full SPA functionality
- Limited community support due to age and lack of recent updates
- More complex setup compared to modern routing solutions in popular frameworks
Code Examples
- Basic route setup:
crossroads.addRoute('/blog/{id}', function(id){
console.log('Blog post id:', id);
});
crossroads.parse('/blog/123'); // outputs: "Blog post id: 123"
- Using optional parameters:
crossroads.addRoute('/search/:query:/:page:?', function(query, page){
console.log('Search query:', query);
console.log('Page:', page || 1);
});
crossroads.parse('/search/javascript/2'); // outputs: "Search query: javascript" and "Page: 2"
crossroads.parse('/search/javascript'); // outputs: "Search query: javascript" and "Page: 1"
- Handling wildcards:
crossroads.addRoute('/{category}/*', function(category, rest){
console.log('Category:', category);
console.log('Rest of the URL:', rest);
});
crossroads.parse('/products/electronics/phones/iphone');
// outputs: "Category: products" and "Rest of the URL: electronics/phones/iphone"
Getting Started
To use Crossroads.js in your project, follow these steps:
- Include the library in your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossroads/0.12.2/crossroads.min.js"></script>
- Set up your routes in your JavaScript file:
crossroads.addRoute('/', function(){
console.log('Home page');
});
crossroads.addRoute('/about', function(){
console.log('About page');
});
crossroads.addRoute('/contact', function(){
console.log('Contact page');
});
// Parse the current URL
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
// Listen for hash changes
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
Note: Crossroads.js is often used in conjunction with the Hasher library for hash-based routing. Make sure to include Hasher as well if you're using this approach.
Competitor Comparisons
Micro client-side router inspired by the Express router
Pros of page.js
- Lightweight and minimalistic, focusing on client-side routing
- Easy to use with a simple API and Express-inspired syntax
- Supports pushState for clean URLs and history manipulation
Cons of page.js
- Less feature-rich compared to Crossroads.js
- Limited built-in support for complex routing scenarios
- May require additional libraries for more advanced functionality
Code Comparison
page.js:
page('/', index)
page('/user/:user', show)
page('/user/:user/edit', edit)
page('*', notfound)
page()
Crossroads.js:
crossroads.addRoute('/', index);
crossroads.addRoute('/user/{user}', show);
crossroads.addRoute('/user/{user}/edit', edit);
crossroads.addRoute('/{*}', notfound);
crossroads.parse(window.location.pathname);
Key Differences
- Syntax: page.js uses a more concise, Express-like syntax, while Crossroads.js uses a more explicit method-based approach
- Flexibility: Crossroads.js offers more advanced routing options and pattern matching
- Size: page.js is generally smaller and more focused on basic routing needs
- Community: Both projects have active communities, but page.js has more recent updates and a larger user base
Use Cases
- Choose page.js for simpler, lightweight client-side routing in small to medium-sized applications
- Opt for Crossroads.js when you need more advanced routing features or greater flexibility in larger applications
A simple vanilla JavaScript router.
Pros of Navigo
- Lightweight and simple to use, with a more modern API
- Built-in support for hash-based routing
- Active development and maintenance
Cons of Navigo
- Less flexible for complex routing scenarios
- Fewer advanced features compared to Crossroads.js
- Smaller community and ecosystem
Code Comparison
Navigo:
const router = new Navigo('/');
router.on('/user/:id', (params) => {
console.log(`User ID: ${params.id}`);
}).resolve();
Crossroads.js:
crossroads.addRoute('/user/{id}', function(id) {
console.log('User ID: ' + id);
});
hasher.init();
Both libraries provide similar functionality for basic routing, but Crossroads.js offers more advanced features for complex routing scenarios. Navigo's syntax is more concise and modern, while Crossroads.js provides greater flexibility and control over route matching and handling.
Navigo is better suited for smaller projects or those requiring simple routing, while Crossroads.js may be preferable for larger applications with complex routing needs. The choice between the two depends on the specific requirements of your project and personal preference for API style.
Declarative routing for React
Pros of React Router
- Designed specifically for React applications, offering seamless integration
- Provides declarative routing with components, making it more intuitive for React developers
- Offers advanced features like nested routing and route-based code splitting
Cons of React Router
- Larger bundle size compared to Crossroads.js, which may impact initial load times
- Steeper learning curve for developers new to React or single-page applications
- Less flexible for use in non-React environments
Code Comparison
React Router:
import { BrowserRouter, Route, Switch } from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route path="/about" component={About} />
<Route path="/" exact component={Home} />
</Switch>
</BrowserRouter>
Crossroads.js:
crossroads.addRoute('/about', function() {
// Handle about route
});
crossroads.addRoute('/', function() {
// Handle home route
});
React Router uses a component-based approach, making it more declarative and aligned with React's philosophy. Crossroads.js, on the other hand, uses a more traditional JavaScript routing approach with function callbacks.
React Router is better suited for React applications, offering tighter integration and more React-specific features. Crossroads.js is more lightweight and flexible, making it a good choice for smaller projects or non-React applications where a simple routing solution is needed.
Pros of reach/router
- Built specifically for React applications, offering seamless integration
- Provides accessible navigation out of the box
- Supports nested routes and relative navigation
Cons of reach/router
- Limited to React applications, not suitable for other frameworks
- Less flexible for complex routing scenarios compared to crossroads.js
- Smaller community and fewer resources available
Code Comparison
reach/router:
import { Router, Link } from "@reach/router"
const App = () => (
<Router>
<Home path="/" />
<Dashboard path="dashboard" />
</Router>
)
crossroads.js:
crossroads.addRoute('/', function() {
// Home route handler
});
crossroads.addRoute('/dashboard', function() {
// Dashboard route handler
});
Key Differences
- reach/router is React-specific, while crossroads.js is framework-agnostic
- reach/router uses JSX for route definition, crossroads.js uses JavaScript functions
- reach/router handles rendering components, crossroads.js focuses on route matching and dispatching
Use Cases
- Choose reach/router for React applications prioritizing accessibility and simplicity
- Opt for crossroads.js when working with non-React projects or requiring more routing flexibility
Community and Maintenance
- reach/router has a smaller but active community focused on React ecosystem
- crossroads.js has a broader user base across various JavaScript projects
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Pros of wouter
- Lightweight and minimalistic, with a smaller bundle size
- Designed specifically for React hooks, offering a more modern API
- Simpler setup and usage, requiring less boilerplate code
Cons of wouter
- Less feature-rich compared to crossroads.js
- Limited to React applications, while crossroads.js is framework-agnostic
- May not be suitable for complex routing scenarios that require advanced features
Code Comparison
wouter:
import { Route, Switch } from "wouter";
<Switch>
<Route path="/users/:id" component={UserProfile} />
<Route path="/about" component={About} />
</Switch>
crossroads.js:
crossroads.addRoute('/users/{id}', function(id){
// Handle user profile
});
crossroads.addRoute('/about', function(){
// Handle about page
});
crossroads.parse(window.location.pathname);
The code comparison demonstrates the simplicity of wouter's React-based approach versus the more flexible but verbose setup of crossroads.js. wouter leverages React components for routing, while crossroads.js uses a more traditional JavaScript routing approach that can be integrated into various frameworks or vanilla JavaScript applications.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Introduction
Crossroads.js is a routing library inspired by URL Route/Dispatch utilities present on frameworks like Rails, Pyramid, Django, CakePHP, CodeIgniter, etc... It parses a string input and decides which action should be executed by matching the string against multiple patterns.
If used properly it can reduce code complexity by decoupling objects and also by abstracting navigation paths.
See project page for documentation and more details.
Links
Dependencies
This library requires JS-Signals to work.
License
Distribution Files
Files inside dist
folder.
- crossroads.js : Uncompressed source code with comments.
- crossroads.min.js : Compressed code.
You can install Crossroads on Node.js using NPM
npm install crossroads
Repository Structure
Folder Structure
dev -> development files
|- lib -> 3rd-party libraries
|- src -> source files
|- tests -> unit tests
dist -> distribution files
Branches
master -> always contain code from the latest stable version
release-** -> code canditate for the next stable version (alpha/beta)
dev -> main development branch (nightly)
gh-pages -> project page
**other** -> features/hotfixes/experimental, probably non-stable code
Building your own
This project uses Node.js for the build process. If for some reason you need to build a custom version install Node.js and run:
node build
This will delete all JS files inside the dist
folder, merge/update/compress source files and copy the output to the dist
folder.
IMPORTANT: dist
folder always contain the latest version, regular users should not need to run build task.
Running unit tests
On the browser
Open dev/tests/spec_runner-dist.html
on your browser.
spec_runner-dist
tests dist/crossroads.js
and spec_runner-dev
tests files inside
dev/src
- they all run the same specs.
On Node.js
Install npm and run:
npm install --dev
npm test
Each time you run npm test
the files inside the dist
folder will be updated
(it executes node build
as a pretest
script).
Top Related Projects
Micro client-side router inspired by the Express router
A simple vanilla JavaScript router.
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot