6
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700">
7
<link rel="stylesheet" href="../../build/cssgrids/grids-min.css">
8
<link rel="stylesheet" href="../assets/css/main.css">
9
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
10
<script src="../../build/yui/yui-min.js"></script>
18
<a href="#toc" class="jump">Jump to Table of Contents</a>
22
<div class="yui3-u-3-4">
24
<div class="content"><div class="intro">
26
Router provides URL-based same-page routing using <a href="https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history">HTML5 history</a> (<code>pushState</code>) or the location hash, depending on what the user's browser supports.
30
This makes it easy to wire up route handlers for different application states while providing full back/forward navigation support and bookmarkable, shareable URLs, all handled entirely on the client.
34
If you've used a server-side routing framework like <a href="http://expressjs.com/">Express</a> or <a href="http://www.sinatrarb.com/">Sinatra</a>, Router will look very familiar to you. This is no accident!
38
<h2 id="getting-started">Getting Started</h2>
41
To include the source files for Router and its dependencies, first load
42
the YUI seed file if you haven't already loaded it.
45
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script></pre>
49
Next, create a new YUI instance for your application and populate it with the
50
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
51
YUI will automatically load any dependencies required by the modules you
55
<pre class="code prettyprint"><script>
56
// Create a new YUI instance and populate it with the required modules.
57
YUI().use('router', function (Y) {
58
// Router is available and ready for use. Add implementation
59
// code here.
61
</script></pre>
65
For more information on creating YUI instances and on the
66
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
67
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
71
<h2 id="upgrading-from-yui-34x">Upgrading from YUI 3.4.x</h2>
74
A beta version of Router was first introduced in YUI 3.4.0, but was named Controller. If you're using Controller in YUI 3.4.0 or 3.4.1, you'll need to make the following changes to your code when upgrading:
80
The name of the class has changed from <code>Controller</code> to <code>Router</code>. Change all references to the <code>Controller</code> class and the <code>controller</code> module in your code to refer to the <code>Router</code> class and <code>router</code> module, respectively. To ease migration, <code>Controller</code> is now an alias for <code>Router</code> and will still work, but this alias will be removed in a future release of YUI.
86
The <code>html5</code>, <code>root</code>, and <code>route</code> properties are now attributes. If you were accessing them as properties, update your code to access them as attributes instead. For example, <code>var root = myController.root;</code> becomes <code>var root = myRouter.get('root');</code>, and <code>myController.root = '/foo';</code> becomes <code>myRouter.set('root', '/foo');</code>.
92
The function signature for route handlers has changed. Previously, the second argument passed to all route handlers was the <code>next()</code> function. As of YUI 3.5.0, the second argument is a response object, and the third argument is the <code>next()</code> function. To preserve backwards compatibility, the response object is also a function that will call <code>next()</code>, but you should still update your code to take the new argument order into account.
97
<h2 id="url-based-routing-on-the-client">URL-based Routing on the Client?</h2>
100
You bet! URLs are an excellent way to maintain state in a web app, since they're easy to read, easy to change, and can be bookmarked and shared.
104
Server-side web frameworks use URLs to maintain state by routing them to different pages and by storing information in query strings. These same techniques can now be used by client-side web apps to achieve better parity with server-side logic and to provide a more seamless user experience.
108
Router allows you to define routes that map to callback functions. Whenever the user navigates to a URL that matches a route you've defined, that route's callback function is executed and can update the UI, make Ajax requests, or perform any other necessary actions. See <a href="#routing">Routing</a> for more details on how this works.
112
Often you'll want to change the URL in order to trigger a route handler, perhaps because the user has taken an action that should change the state of your application. Router provides a <code>save()</code> method that sets a new URL and saves it to the user's browser history. There's also a <code>replace()</code> method to replace the current URL in the user's browser history without creating a new entry. The <a href="#updating-the-url">Updating the URL</a> section describes these methods in detail.
115
<h2 id="sample-urls">Sample URLs</h2>
118
In browsers that support the HTML5 history API, Router generates real URLs that can gracefully degrade to allow server-side handling of initial pageviews or pageviews without JS enabled. Most modern browsers (including recent versions of Firefox, Chrome, Safari, and Mobile Safari) support HTML5 history.
122
In browsers that don't support the HTML5 history API, Router falls back on using the location hash to store URL information and trigger history changes. This mostly applies only to older browsers and Internet Explorer. Unfortunately, even Internet Explorer 9 doesn't support the HTML5 history API.
126
The table below contains examples of the kinds of URLs Router might generate when the <code>save()</code> method is called on a Router instance, starting from an initial URL of <code>http://example.com/</code>.
139
<td><code>router.save('/')</code></td>
140
<td><code>http://example.com/</code></td>
141
<td><code>http://example.com/#/</code></td>
145
<td><code>router.save('/pie/yum')</code></td>
146
<td><code>http://example.com/pie/yum</code></td>
147
<td><code>http://example.com/#/pie/yum</code></td>
151
<td><code>router.save('/pie?type=pecan&icecream=true')</code></td>
152
<td><code>http://example.com/pie?type=pecan&icecream=true</code></td>
153
<td><code>http://example.com/#/pie?type=pecan&icecream=true</code></td>
158
<h2 id="using-router">Using Router</h2>
160
<h3 id="instantiating-router">Instantiating Router</h3>
163
To begin adding route handlers, the first thing you'll need to do is create a new Router instance.
166
<pre class="code prettyprint">var router = new Y.Router();</pre>
170
This is the simplest way of working with Router, but you may also extend <code>Y.Router</code> to create a custom Router class that suits your needs. The <a href="#extending-yrouter">Extending <code>Y.Router</code></a> section explains how to do this.
173
<h4 id="config-attributes">Config Attributes</h4>
176
When instantiating Router, you may optionally pass in a config object containing values for any of the following attributes. For more details on these attributes, see Router's <a href="http://yuilibrary.com/yui/docs/api/modules/router.html">API docs</a>.
189
<td><code>html5</code></td>
190
<td><em>auto</em></td>
193
Whether or not to use HTML5 history (<code>true</code>) or hash-based history (<code>false</code>).
197
Feature detection is used to determine the correct default setting for the current browser, but you may override this to force all browsers to use or not use HTML5 history.
201
Before changing this value, please read <a href="#html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</a> and be sure you fully understand the consequences. It's almost always a better idea to leave it alone.
207
<td><code>root</code></td>
208
<td><code>''</code></td>
211
Root path from which all routes should be evaluated. See <a href="#setting-the-root-path">Setting the Root Path</a> for details.
217
<td><code>routes</code></td>
218
<td><code>[]</code></td>
221
Array of route objects. This can be used to specify routes at instantiation time, or when extending <code>Y.Router</code>. It can also be used after instantiation to reset all existing routes. To add routes after instantiation without resetting existing routes, use the <code>route()</code> method.
225
Each item in the array must be an object with the following properties:
228
<dl style="margin-top:1em">
229
<dt><code>path</code></dt>
231
String or regex representing the path to match. See <a href="#routing">Routing</a> for more details.
234
<dt><code>callback</code></dt>
236
A function or a string representing the name of a function on the Router instance that should be called when the route is triggered. See <a href="#routing">Routing</a> for more details.
245
Here's an example that sets all the configurable attributes at instantiation time:
248
<pre class="code prettyprint">var router = new Y.Router({
250
root : '/mysite',
253
{path: '/', callback: function () { alert('Hello!'); }},
254
{path: '/pie', callback: function () { alert('Mmm. Pie.'); }}
259
<h4 id="setting-the-root-path">Setting the Root Path</h4>
262
Let's say the URL for your website is <code>http://example.com/mysite/</code>. Since Router matches routes based on the URL path, it would look for routes beginning with <code>/mysite/</code>.
266
You could deal with this by ensuring that all your routes start with <code>/mysite/</code>, but that's tedious, and it won't work well if you're writing a component that might be used on various sites where you can't anticipate the root path.
270
This is where the <code>root</code> config attribute comes in. If you set <code>root</code> to <code>'/mysite'</code>, then all routes will be evaluated relative to that root path, as illustrated below.
274
The <code>root</code> must be an absolute path.
281
<th>Route (No root)</th>
282
<th>Route (Root: /mysite)</th>
287
<td><code>http://example.com/mysite/</code></td>
288
<td><code>/mysite/</code></td>
289
<td><code>/</code></td>
293
<td><code>http://example.com/mysite/pie/</code></td>
294
<td><code>/mysite/pie/</code></td>
295
<td><code>/pie/</code></td>
299
<td><code>http://example.com/mysite/ice-cream/yum.html</code></td>
300
<td><code>/mysite/ice-cream/yum.html</code></td>
301
<td><code>/ice-cream/yum.html</code></td>
306
<h3 id="extending-yrouter">Extending <code>Y.Router</code></h3>
309
While <code>Y.Router</code> may be instantiated and used directly, you might find it more convenient to extend the <code>Y.Router</code> class to create a subclass customized for your particular needs.
313
Use the <code>Y.Base.create()</code> method to extend <code>Y.Router</code> and add or override prototype and static members and attributes. You may also optionally specify one or more <a href="../base/index.html#extensions">Base extensions</a> to mix into your new class.
316
<pre class="code prettyprint">// Create a Y.CustomRouter class that extends Y.Router.
317
Y.CustomRouter = Y.Base.create('customRouter', Y.Router, [], {
318
// Add or override prototype properties and methods here.
320
// Add static properties and methods here.
323
// Override default attributes here.
329
One benefit of extending <code>Y.Router</code> is that you can easily add default routes and route handlers to your custom Router class, and they'll be shared by all instances of that class unless overridden at the instance level:
332
<pre class="code prettyprint">Y.CustomRouter = Y.Base.create('customRouter', Y.Router, [], {
333
// Default route handlers inherited by all CustomRouter instances.
334
index: function (req) {
335
// ... handle the / route ...
338
pie: function (req) {
339
// ... handle the /pie route ...
343
// Evaluate all routes relative to this root path.
345
value: '/mysite'
348
// Share these default routes with all CustomRouter instances.
351
{path: '/', callback: 'index'},
352
{path: '/pie', callback: 'pie'}
358
// Create a CustomRouter instance that inherits the defaults and adds to
360
var router = new Y.CustomRouter();
362
router.route('/cheesecake', function (req) {
363
// ... handle the /cheesecake route
368
Now all instances of <code>Y.CustomRouter</code> will inherit all the custom defaults and can add to or override them. The <code>router</code> instance created here will handle the <code>/</code> and <code>/pie</code> routes in addition to its own <code>/cheesecake</code> route, and will evaluate all routes from the <code>/mysite</code> root path.
371
<h3 id="routing">Routing</h3>
374
Use the <code>route()</code> method to add a new route to a Router instance. The first parameter is a path specification or regular expression that the URL path must match, and the second parameter is a callback function or function name to execute when the route is matched.
377
<pre class="code prettyprint">var router = new Y.Router();
379
// Add a route using a string as the path specification.
380
router.route('/pie', function () {
381
Y.log('You visited http://example.com/pie');
384
// Add a route using a regular expression as the path specification.
385
router.route(/^\/cake$/, function () {
386
Y.log('You visited http://example.com/cake');
391
Routes are always evaluated in the order they're added. The first route that matches a given URL is executed, and any subsequent routes that also match the URL will not be executed unless the first route passes control to the next route. See <a href="#chaining-routes">Chaining Routes</a> for more info on executing more than one route for a given URL.
395
When a route callback is specified as a string instead of a function, it's assumed to represent the name of a function on the Router instance.
398
<pre class="code prettyprint">var router = new Y.Router();
400
router.pie = function () {
401
Y.log('You visited http://example.com/pie');
404
// Add a route using router.pie as the route callback.
405
router.route('/pie', 'pie');</pre>
409
As an alternative to using the <code>route()</code> method, routes may be added at instantiation time using the <code>routes</code> config attribute:
412
<pre class="code prettyprint">var router = new Y.Router({
414
{path: '/pie', callback: function () {
415
Y.log('You visited http://example.com/pie');
418
{path: /^\/cake$/, callback: function () {
419
Y.log('You visited http://example.com/cake');
426
This is functionally equivalent to adding the routes via the <code>route()</code> method, except that it will replace any default routes, and the routes are added during the Router's initialization stage rather than after.
429
<h4 id="paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</h4>
432
A route path may be specified as either a string or a regular expression. When a string is provided, it's compiled to a regular expression internally. If the regex matches the path portion (not including protocol, domain, query string, etc.) of a URL being dispatched, the route callback will be executed.
436
Path strings may contain placeholders. When a route is matched, the values of these placeholders will be made available to the route callback on the <code>req.params</code> object.
440
A placeholder prefixed by a <code>:</code>, like <code>:pie</code>, will match any character except for a path separator (<code>/</code>).
443
<pre class="code prettyprint">router.route('/pie/:type/:slices', function (req) {
444
Y.log("You ordered " + req.params.slices + " slices of "
445
+ req.params.type + " pie.");
448
router.save('/pie/apple/2');
449
// => "You ordered 2 slices of apple pie."
451
router.save('/pie/lemon+meringue/42');
452
// => "You ordered 42 slices of lemon meringue pie."</pre>
456
A placeholder prefixed by a <code>*</code>, like <code>*path</code>, will match as many characters as it can until the next character after the placeholder, including path separators.
459
<pre class="code prettyprint">router.route('/files/*path', function (req) {
460
Y.log("You requested the file " + req.params.path);
463
router.save('/files/recipes/pie/pecan.html');
464
// => "You requested the file recipes/pie/pecan.html"</pre>
468
Use <code>*</code> all by itself as a wildcard to match any path at all:
471
<pre class="code prettyprint">router.route('*', function () {
472
Y.log("Wildcard route! I match everything! I'm craaaaaaazy!");
475
router.save('/purple/monkey/dishwasher');
476
// => "Wildcard route! I match everything! I'm craaaaaaazy!"
478
router.save('/blue/jeans/pizza');
479
// => "Wildcard route! I match everything! I'm craaaaaaazy!"</pre>
483
Wildcards can also be used within a path:
486
<pre class="code prettyprint">router.route('/purple/*', function () {
487
Y.log("I only like purple stuffz!");
490
router.save('/purple/monkey/dishwasher');
491
// => "I only like purple stuffz!"
493
router.save('/purple/pants');
494
// => "I only like purple stuffz!"</pre>
498
Placeholder names may contain any character in the range <code>[A-Za-z0-9_-]</code> (so <code>:foo-bar</code> is a valid placeholder but <code>:foo bar</code> is not).
502
When a regular expression is used as a path specification, <code>req.params</code> will be an array. The first item in the array is the entire matched string, and subsequent items are captured subpattern matches (if any).
505
<pre class="code prettyprint">router.route(/^\/pie\/([^\/]*)\/([^\/]*)$/, function (req) {
506
Y.log("You ordered " + req.params[1] + " slices of "
507
+ req.params[2] + " pie.");
510
router.save('/pie/maple+custard/infinity');
511
// => "You ordered infinity slices of maple custard pie."</pre>
514
<h4 id="route-callbacks">Route Callbacks</h4>
517
When a route is matched, the callback function associated with that route will be executed, and will receive three parameters:
521
<dt><strong><code>req</code> (Object)</strong></dt>
524
An object that contains information about the request that triggered the route. It contains the following properties:
528
<dt><strong><code>params</code> (Object or Array)</strong></dt>
531
Parameters matched by the route path specification.
535
If a string path was used and contained named parameters, then <code>params</code> will be a hash with parameter names as keys and the matched substrings as values. If a regex path was used, <code>params</code> will be an array of matches starting at index <code>0</code> for the full string matched, then <code>1</code> for the first subpattern match, and so on.
539
<dt><strong><code>path</code> (String)</strong></dt>
542
The current URL path matched by the route.
546
<dt><strong><code>query</code> (Object)</strong></dt>
549
Hash of query string parameters and values specified in the URL, if any.
553
<dt><strong><code>url</code> (String)</strong></dt>
560
<dt><strong><code>src</code> (String)</strong></dt>
563
What initiated the dispatch.
567
In an HTML5 browser, when the back/forward buttons are used, this property will have a value of "popstate".
573
<dt><strong><code>res</code> (Object)</strong></dt>
576
An object that contains methods and information that relate to responding to a request.
580
<strong>Note:</strong> For backwards compatibility, the response object is also a function that when called will behave the same as directly calling <code>next()</code>. This backcompat behavior will eventually be removed.
584
The response object contains the following properties (it will eventually contain more, and may be augmented by subclasses or used to pass information from route to route):
588
<dt><strong><code>req</code> (Object)</strong></dt>
591
Reference to the request object.
597
<dt><strong><code>next</code> (Function)</strong></dt>
600
A function that will pass control to the next matching route (if any) when called. If not called, no further routes will be executed.
606
Inside a route callback, the <code>this</code> keyword will always refer to the Router instance that executed that route.
609
<h4 id="chaining-routes">Chaining Routes</h4>
612
By default, only the first route that matches a URL will be executed, even if there are several routes that match. However, when a route is executed, it will receive a <code>next()</code> function as its third parameter. Calling this function will execute the next matching route if there is one.
615
<pre class="code prettyprint">router.route('/pie', function (req, res, next) {
616
Y.log('Callback #1 executed!');
620
router.route('/pie', function (req) {
621
Y.log('Callback #2 executed!');
624
router.route('/pie', function (req) {
625
Y.log('Callback #3 executed!');
628
router.save('/pie');
629
// => "Callback #1 executed!"
630
// => "Callback #2 executed!"</pre>
634
If you want the first route callback to pass some data along to subsequent callbacks, you can attach that data to either the <code>req</code> object or the <code>res</code> object, which are shared between all routes that are executed during a single request.
637
<pre class="code prettyprint">router.route('/ice-cream', function (req, res, next) {
638
req.flavor = 'cookie dough';
642
router.route('/ice-cream', function (req) {
643
Y.log("I sure do like " + req.flavor + " ice cream.");
646
router.save('/ice-cream');
647
// => "I sure do like cookie dough ice cream."</pre>
651
Whether to store data on <code>req</code> or <code>res</code> is up to you, but by convention, data pertaining to the request should be stored on <code>req</code>, and data pertaining to a response or to some other result of that request should be stored on <code>res</code>.
654
<h3 id="updating-the-url">Updating the URL</h3>
657
Call the <code>save()</code> or <code>replace()</code> methods to update the URL and store an entry in the browser's history.
661
The only difference between the two is that <code>save()</code> saves a new history entry, while <code>replace()</code> replaces the current history entry.
664
<pre class="code prettyprint">// Save a new history entry.
665
router.save('/cake');
667
// Replace the current history entry with a new one.
668
router.replace('/pie');</pre>
672
Changing the URL in this way will trigger a dispatch, and will execute the first route that matches the new URL (if any). A dispatch will also be triggered automatically whenever the user uses the browser's back or forward buttons.
676
When you need to provide state information to your route handlers, it's best to provide that information as query parameters in the URL. This way, your application's state is always reflected in the current URL, and can be properly restored when a URL is bookmarked or copied.
679
<pre class="code prettyprint">router.route('/ice-cream', function (req) {
680
var flavor = req.query.flavor;
682
if (flavor === 'vanilla') {
683
Y.log('Vanilla? How boring.');
684
} else if (flavor === 'americone dream') {
685
Y.log('Mmmm, Colbert-flavored ice cream.');
687
Y.log('Error! Error! Does not compute!');
691
router.save('/ice-cream?flavor=vanilla');
692
// => "Vanilla? How boring."
694
router.save('/ice-cream?flavor=americone+dream');
695
// => "Mmm, Colbert-flavored ice cream."
697
router.save('/ice-cream?flavor=kitten');
698
// => "Error! Error! Does not compute!"</pre>
701
<h4 id="capturing-link-clicks">Capturing Link Clicks</h4>
704
An excellent way to provide progressive enhancement on a page with URLs that can be handled by both the server and the client is to use normal links, and then add a delegated event handler to capture clicks on those links and use client-side routing when JavaScript is available. You can also use this technique to selectively use client-side routing or server-side routing depending on which link is clicked.
707
<pre class="code prettyprint">// This sample requires the `node-event-delegate` module.
708
YUI().use('router', 'node-event-delegate', function (Y) {
709
// ... create a router instance as described in the sections above ...
711
// Attach a delegated click handler to listen for clicks on all links on the
713
Y.one('body').delegate('click', function (e) {
714
// Allow the native behavior on middle/right-click, or when Ctrl or Command
715
// are pressed.
716
if (e.button !== 1 || e.ctrlKey || e.metaKey) {
720
// Remove the non-path portion of the URL, and any portion of the path that
721
// isn't relative to this router's root path.
722
var path = router.removeRoot(e.currentTarget.get('href'));
724
// If the router has a route that matches this path, then use the
725
// router to update the URL and handle the route. Otherwise, let the
726
// browser handle the click normally.
727
if (router.hasRoute(path)) {
736
Now a click on any link, such as <code><a href="http://example.com/foo">Click me!</a></code>, will automatically be handled by the router if there's a matching route. If there's no matching route, or if the user doesn't have JavaScript enabled, the link click will be handled normally by the browser.
739
<h3 id="to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</h3>
742
Dispatching is what it's called when Router looks for routes that match the current URL and then executes the callback of the first matching route (if any).
746
A dispatch can be triggered in the following ways:
750
<li>Automatically, whenever the URL changes after the initial pageview.</li>
751
<li>Manually, by calling the <code>dispatch()</code> method.</li>
752
<li>Manually (but only in HTML5 browsers), by calling the <code>upgrade()</code> method when the URL contains a hash-based route that was copied from a legacy browser.</li>
756
It's important to remember that if a user bookmarks or copies an HTML5 URL generated by Router and visits that URL later, the full URL will be sent to the server. On the other hand, if a user bookmarks or copies a hash-based URL in a legacy browser and then visits it later, the hash portion of the URL <em>won't</em> be sent to the server.
760
For instance, let's say a user visits your website at <code>http://example.com/</code>. On that page, you have the following code:
763
<pre class="code prettyprint"><button id="pie">Click me if you like pie!</button>
766
YUI().use('router', 'node', function (Y) {
767
var router = new Y.Router();
769
router.route('/pie', function () {
770
// Show the user a photo of a delicious pie.
773
Y.one('#pie').on('click', function () {
774
router.save('/pie');
777
</script></pre>
781
In an HTML5 browser, when the user clicks the button, Router will change the URL to <code>http://example.com/pie</code> and then execute the <code>/pie</code> route, but the browser won't contact the server. If the user bookmarks this URL and then loads it again later, the web server will handle the request. If it doesn't recognize the path <code>/pie</code>, it may return a 404 error, which would be no good.
785
In a legacy browser, clicking the button will cause the URL to change to <code>http://example.com/#/pie</code>, and the <code>/pie</code> route will be executed, also without contacting the server. The difference is that if the user bookmarks this URL and loads it later, the hash portion won't be sent to the server. The server will only see <code>http://example.com/</code>, so it will be necessary to handle the request on the client as well.
789
There are two ways to deal with this. One way would be to implement server-side logic to handle requests for <code>/pie</code> and render the appropriate page. To provide fallback support for hash-based URLs, we can modify the client-side code to call the <code>dispatch()</code> method in legacy browsers, by adding the following:
792
<pre class="code prettyprint">// Always dispatch to an initial route on legacy browsers. Only dispatch to an
793
// initial route on HTML5 browsers if it's necessary in order to upgrade a
794
// legacy hash URL to an HTML5 URL.
795
if (router.get('html5')) {
803
The benefit of this is that HTML5 URLs will be rendered on the server and won't present any difficulties for search crawlers or users with JS disabled. Meanwhile, hash-based URLs will be handled on the client as long as JS is enabled. The drawback with this method is that it may require maintaining duplicate logic on both the server and the client.
807
The other way to handle this would be to configure the server to render the same initial page for all URLs (it would essentially route all paths to the same page), and always dispatch on the client, regardless of the browser's capabilities:
810
<pre class="code prettyprint">// Dispatch to an initial route on all browsers.
811
router.dispatch();</pre>
815
On the one hand, this solution avoids most of the server-side complexity and keeps all the router logic on the client. On the other, it requires the client to support JavaScript, so it won't play well with search crawlers that can't run JavaScript or users who disable JavaScript.
818
<h2 id="best-practices">Best Practices</h2>
820
<h3 id="html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</h3>
823
As discussed in <a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>, there are benefits and drawbacks to both HTML5 URLs—that is, URLs generated via the HTML5 history API—and hash-based URLs. This adds difficulty to any client-side URL-based routing solution, and unfortunately it means you may need to make some tough choices about the architecture of your application.
827
The primary benefit of HTML5 URLs is that they can potentially be handled on the server as well as on the client. This has potential benefits for application architecture (rendering an initial pageview on the server is often faster than rendering it on the client) and for preventing link rot (if you rewrite or replace your application at some point, it's relatively easy to set up server-side redirects to point the old URLs to a new location). That said, HTML5 URLs may require more server-side logic in order to work correctly.
831
Hash-based URLs, on the other hand, can't be handled on the server because browsers don't send the hash portion of a URL to a server. This means they must always be rendered on the client using JavaScript. Even worse, if you eventually rewrite or replace your web app, it's extremely unlikely that you'll be able to keep that old JavaScript around just for the sake of redirecting old URLs, which means any old hash-based URLs in the wild are likely to stop working.
835
In general, the benefits of HTML5 URLs tend to outweigh the drawbacks when compared to hash-based URLs, which is why Router automatically defaults to using HTML5 URLs in browsers that support it. The hash-based URLs generated by Router should be used only as a fallback for legacy browsers.
838
<h3 id="cross-browser-url-compatibility">Cross-browser URL Compatibility</h3>
841
It's very important that any URL generated by Router be usable in any browser. If a user of a legacy browser copies a URL and shares it with a friend who uses an HTML5 browser, that URL should still work. And if someone copies an HTML5 URL and shares it with a user of a legacy browser, that needs to work too.
845
When a hash-based URL is loaded in an HTML5 browser and <code>dispatch()</code> or <code>upgrade()</code> are called, Router automatically upgrades the URL to an HTML5 URL. So a URL like <code>http://example.com/#/pie</code> will become <code>http://example.com/pie</code>, and the HTML5 browser will execute the appropriate route handler.
849
The difference between the <code>dispatch()</code> and <code>upgrade()</code> methods is that <code>dispatch()</code> always dispatches to the first route that matches the current URL, whereas <code>upgrade()</code> will only dispatch if the browser is an HTML5 browser and the URL is a legacy hash-based URL that must be handled on the client in order to upgrade it to an HTML5 URL.
853
When an HTML5 URL like <code>http://example.com/pie</code> is loaded in a legacy browser, what happens depends on how your server is configured:
857
<li><p>If the server is capable of handling the URL, then it should render the page in the appropriate state, and Router won't need to do anything.</p></li>
858
<li><p>If the server is not capable of handling the URL, then it should render the initial page state and you should call Router's <code>dispatch()</code> method. Router will parse the HTML5 URL and execute the appropriate route, even in a legacy browser.</p></li>
862
For more on how dispatching works, see <a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>.
865
<h3 id="progressive-enhancement-and-seo">Progressive Enhancement and SEO</h3>
868
In general, HTML5 URLs that can be rendered by the server when necessary provide the best support for both progressive enhancement (by rendering initial pageviews more quickly, even in browsers with JavaScript disabled) and for search engine optimization (by allowing you to use real, non hash-based URLs that can be crawled by search bots, which may not support JavaScript).
872
Being able to render the same application states both on the server and the client may require you to write duplicate code. However, if you use JavaScript on the server, and in particular if you use <a href="http://nodejs.org/">Node.js</a>, you may be able to share code.
876
Router's routing style and route specification format are intentionally very similar to those of the <a href="http://expressjs.com/">Express.js</a> server-side framework. With a little care, you may be able to use the same route handler code on both the server and the client.
879
<h4 id="supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</h4>
882
One of the problems with the hash-based URLs Router uses to support legacy browsers is that most search engines don't distinguish between a URL with a hash fragment and one without. This means that, to a search bot, the URLs <code>http://example.com/</code> and <code>http://example.com/#/pie</code> might look the same, even though they might represent completely different content in your application.
886
Google's <a href="http://code.google.com/web/ajaxcrawling/">Ajax Crawling Scheme</a> specifies a way to make hash-based URLs crawlable by the GoogleBot if you're willing to implement some extra server-side logic.
890
To indicate to the GoogleBot that your hash URLs are crawlable, the hash must be prefixed by <code>#!</code> instead of the default <code>#</code>. You can make Router do this automatically by setting the value of the static <code>Y.HistoryHash.hashPrefix</code> property before initializing any Router instances:
893
<pre class="code prettyprint">Y.HistoryHash.hashPrefix = '!';</pre>
897
Next, read Google's <a href="http://code.google.com/web/ajaxcrawling/docs/getting-started.html">getting started guide</a> for a description of how the Ajax crawling scheme works and the additional changes you'll need to make to your application. Most of the changes you'll need to make will have to happen in your server-side logic.
901
Don't skip the server-side changes! Without them, using the <code>#!</code> prefix won't do you any good, and may even hurt the search ranking of your pages.
904
<h2 id="known-limitations">Known Limitations</h2>
907
<li><p><strong>HTML5 history is not supported by Internet Explorer 9 or lower.</strong> IE10 is the first version of Internet Explorer that supports HTML5 history. Earlier versions will fall back to hash-based history by default.</p></li>
909
<li><p><strong>Android 2.x is forced to use hash-based history due to <a href="http://code.google.com/p/android/issues/detail?id=17471">a bug</a> in Android's HTML5 history implementation.</strong> This bug does not affect Android 3.0 and higher.</p></li>
911
<li><p><strong>Hash-based URLs are case-insensitive in Internet Explorer 8 and 9</strong>. Most browsers follow the HTML5 spec and treat URLs—including hash-based URLs—as case-sensitive. IE8 and IE9 ignore case in hash-based URLs, so changing a hash-based URL from <code>/foo</code> to <code>/Foo</code> won't trigger a dispatch.</p></li>
913
<li><p><strong>Internet Explorer 6 and 7 only retain the most recent hash-based URL from a previous pageview after navigating to another page and returning.</strong> However, history entries created within a single pageview will persist for the duration of that pageview, and bookmarked URLs will still work in all cases.</p></li>
915
<li><p><strong>In Internet Explorer 6 and 7, the page titles displayed for history entries in the browser's history dropdown menu are not correct.</strong> Instead of showing the title of each page, it shows part of the URL of each page.</p></li>
917
<li><p><strong>Internet Explorer (all versions) replaces the current history entry when the hash portion of the URL is manually edited in the URL bar</strong> instead of adding a new history entry as other browsers do. There's unfortunately nothing YUI can do to detect or work around this.</p></li>
923
<div class="yui3-u-1-4">
924
<div class="sidebar">
926
<div id="toc" class="sidebox">
928
<h2 class="no-toc">Table of Contents</h2>
934
<a href="#getting-started">Getting Started</a>
937
<a href="#upgrading-from-yui-34x">Upgrading from YUI 3.4.x</a>
940
<a href="#url-based-routing-on-the-client">URL-based Routing on the Client?</a>
943
<a href="#sample-urls">Sample URLs</a>
946
<a href="#using-router">Using Router</a>
949
<a href="#instantiating-router">Instantiating Router</a>
952
<a href="#config-attributes">Config Attributes</a>
955
<a href="#setting-the-root-path">Setting the Root Path</a>
960
<a href="#extending-yrouter">Extending <code>Y.Router</code></a>
963
<a href="#routing">Routing</a>
966
<a href="#paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</a>
969
<a href="#route-callbacks">Route Callbacks</a>
972
<a href="#chaining-routes">Chaining Routes</a>
977
<a href="#updating-the-url">Updating the URL</a>
980
<a href="#capturing-link-clicks">Capturing Link Clicks</a>
985
<a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>
990
<a href="#best-practices">Best Practices</a>
993
<a href="#html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</a>
996
<a href="#cross-browser-url-compatibility">Cross-browser URL Compatibility</a>
999
<a href="#progressive-enhancement-and-seo">Progressive Enhancement and SEO</a>
1002
<a href="#supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</a>
1009
<a href="#known-limitations">Known Limitations</a>
1024
<script src="../assets/vendor/prettify/prettify-min.js"></script>
1025
<script>prettyPrint();</script>