operator
1.8kb drop-in "PJAX" solution for fluid, smooth transitions between pages. Zero stress.
Features
- Advanced routing via matchit
- Client-side redirects
- Async-by-default, easy data loading between routes
- Pages are cached after initial visit
- Pre-fetch select pages, as needed
Install
npm i operator --save
Usage
Basically zero config by default, just specify a root DOM node to attach to.
Defining routes
To define custom handlers for a given route, pass an object with a path
property and handler
method.
Routes handlers can also return Promise
s, and they support params, optional
params, and wildcards.
Route Caching
Routes are cached by default, so on subsequent visits, no data will be loaded.
To follow links to pages via AJAX, but fetch fresh content on each navigation
action, set cache
to false
:
Ignoring Routes
Sometimes you need to navigate to a page without AJAX, perhaps to load some sort
of iframe
content. To do so, set ignore
to true
:
Lifecycle
Any function passed to the route config will be called on every route change, kind of like middleware.
const app =
Operator also emits some helpful events.
app // on valid link clickapp // before renderapp // after renderapp // when the URL contains a hash
History state
Operator does not manage History
or page title, for maximum flexibility to the
user. Most people should probably just use this snippet:
app
If you want to ignore things like query strings or hashes, use pathname
:
app
Hash Anchors
When a hash is encountered – whether on a navigate
action between pages, or
for scroll-anchors on the same page - Operator will emit a hash
event. It's
up to you to handle scrolling.
For most sites, this should work:
app
Smooth scrolling is also pretty easy:
app
API
go(path)
app
load(path)
Use this for prefetching pages.
app
state (getter)
appstate // => { previousDocument, pathname, location, params, hash, search, handler }
Recipes
Redirects
app
Transition animation
Changelog
v1.8.0
Removed default scroll handling. This should be moved to user-space in the event the user doesn't want the page to reset to the top.
v1.7.0
Added previousDocument
(a complete cloned document
object) to the state
object. Replaces state.title
via previousDocument.title
.
v1.6.0
- Implemented
hash
event, see docs - Fix bad
mailto
andtel
regex, thanks @gabrielloeb!
v1.2.0
Slight update to the API, will require brief migration to new syntax for most users.
- Deprecated Array format for route configs in favor of more flexible Object syntax
- Add
ignore
andcache
options
License
MIT License © Eric Bailey