README.md
A simple front-end routing for your pages. It loads the script only when the DOM is ready. It can handle both Regex and paths
Parameters
pagex(path, [negate?], callback);
- path: the path or regex to be matched against the current url
- negate (optional): set to true to call the function if NOT in this path. Really useful for the difficulty to do so otherwise
- callback: the callback to call if the path matches (or if it doesn't and it's negated)
Pseudo Example
If you have a large javascript codebase, you can split it the following way:
// Logic for all your pages. For example, analyticsanalytics();// Logic specific for your /users page and subpagespagex('/users', function(){// ...
});// Logic specific for your /books page and subpagespagex('/books', function(){// ...
});
Path
A simple front-end router based on express.js router, which is based on path-to-regexp:
pagex('/hi', function(){alert('Hi there!');
});
You can get the url parameters easily:
pagex('/users/:username', function(username){alert('Hi there '+ username +'!');
});
Make them optional:
// Note: ES6 default parameter shown herepagex('/users/:username?', function(username='everyone'){alert('Hi there '+ username +'!');
});
Regex
Originally the main way of doing this was with pure regex (that's why it's called pagex, from Page + Regex). However, the main way now is with paths that get converted internally to regex. If you want to use regex you can do so:
// Starts by a stringpagex(/^\/user/, function(){console.log("User section loaded");
});// When NOT in this page, since negating in regex is complex: stackoverflow.com/a/1240337pagex(/^\/user/, true, function(){console.log("User index");
});// Strict pagepagex(/^\/user$/, function(){console.log("User index");
});// Parameters from capturing groups, with required idpagex(/^\/user\/([A-Za-z0-9]+)/, function(id){console.log("Hello user "+ id +"!");
});// Parameters from capturing groups, with optional idpagex(/^\/user\/?([A-Za-z0-9]+)?/, function(id){console.log("Are you there, user "+ id +"?");
});