5
<title>Controller</title>
6
<link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
7
<link rel="stylesheet" href="../assets/css/main.css">
8
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
9
<script src="../../build/yui/yui-min.js"></script>
17
<a href="#toc" class="jump">Jump to Table of Contents</a>
21
<div id="main" class="yui3-u">
22
<div class="content"><div class="intro">
24
Controller 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.
28
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.
32
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>, Controller will look very familiar to you. This is no accident!
36
<h2 id="getting-started">Getting Started</h2>
39
To include the source files for Controller and its dependencies, first load
40
the YUI seed file if you haven't already loaded it.
43
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script></pre>
47
Next, create a new YUI instance for your application and populate it with the
48
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
49
YUI will automatically load any dependencies required by the modules you
53
<pre class="code prettyprint">// Create a new YUI instance and populate it with the required modules.
54
YUI().use('controller', function (Y) {
55
// Controller is available and ready for use. Add implementation
56
// code here.
61
For more information on creating YUI instances and on the
62
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
63
documentation for the <a href="../yui/index.html">YUI Global object</a>.
67
<h2 id="url-based-routing-on-the-client">URL-based Routing on the Client?</h2>
70
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.
74
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.
78
Controller 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.
82
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. Controller 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.
85
<h2 id="sample-urls">Sample URLs</h2>
88
In browsers that support the HTML5 history API, Controller 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.
92
In browsers that don't support the HTML5 history API, Controller 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.
96
The table below contains examples of the kinds of URLs Controller might generate when the <code>save()</code> method is called on a Controller instance, starting from an initial URL of <code>http://example.com/</code>.
109
<td><code>controller.save('/')</code></td>
110
<td><code>http://example.com/</code></td>
111
<td><code>http://example.com/#/</code></td>
115
<td><code>controller.save('/pie/yum')</code></td>
116
<td><code>http://example.com/pie/yum</code></td>
117
<td><code>http://example.com/#/pie/yum</code></td>
121
<td><code>controller.save('/pie?type=pecan&icecream=true')</code></td>
122
<td><code>http://example.com/pie?type=pecan&icecream=true</code></td>
123
<td><code>http://example.com/#/pie?type=pecan&icecream=true</code></td>
128
<h2 id="using-controller">Using Controller</h2>
130
<h3 id="instantiating-controller">Instantiating Controller</h3>
133
To begin adding route handlers, the first thing you'll need to do is create a new Controller instance.
136
<pre class="code prettyprint">var controller = new Y.Controller();</pre>
140
This is the simplest way of working with Controller, but you may also extend <code>Y.Controller</code> to create a custom Controller class that suits your needs. The <a href="#extending-ycontroller">Extending <code>Y.Controller</code></a> section explains how to do this.
143
<h4 id="config-properties">Config Properties</h4>
146
When instantiating Controller, you may optionally pass in a config object containing any of the following properties. For more details on these properties, see Controller's <a href="http://yuilibrary.com/yui/docs/api/modules/module_controller.html">API docs</a>.
159
<td><code>root</code></td>
160
<td><code>''</code></td>
163
Root path from which all routes should be evaluated. See <a href="#setting-the-root-path">Setting the Root Path</a> for details.
169
<td><code>routes</code></td>
170
<td><code>[]</code></td>
173
Array of route objects specifying routes to be created at instantiation time. This can be used as an alternative to adding routes via the <code>route()</code> method after instantiation.
177
Each item in the array must be an object with the following properties:
180
<dl style="margin-top:1em">
181
<dt><code>path</code></dt>
183
String or regex representing the path to match. See <a href="#routing">Routing</a> for more details.
186
<dt><code>callback</code></dt>
188
A function or a string representing the name of a function on the Controller instance that should be called when the route is triggered. See <a href="#routing">Routing</a> for more details.
197
Here's an example that sets all the configurable properties:
200
<pre class="code prettyprint">var controller = new Y.Controller({
201
root: '/mysite',
204
{path: '/', callback: function () { alert('Hello!'); }},
205
{path: '/pie', callback: function () { alert('Mmm. Pie.'); }}
210
<h4 id="read-only-properties">Read-Only Properties</h4>
213
Controller instances currently expose a single informational property, <code>html5</code>, which is meant to be read-only.
225
<td><code>html5</code></td>
228
Whether or not the user's browser is capable of using HTML5 history.
232
This property is for informational purposes only. It's not configurable, and changing it will have no effect.
239
<h4 id="setting-the-root-path">Setting the Root Path</h4>
242
Let's say the URL for your website is <code>http://example.com/mysite/</code>. Since Controller matches routes based on the URL path, it would look for routes beginning with <code>/mysite/</code>.
246
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.
250
This is where the <code>root</code> config property 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.
254
The <code>root</code> must be an absolute path.
261
<th>Route (No root)</th>
262
<th>Route (Root: /mysite)</th>
267
<td><code>http://example.com/mysite/</code></td>
268
<td><code>/mysite/</code></td>
269
<td><code>/</code></td>
273
<td><code>http://example.com/mysite/pie/</code></td>
274
<td><code>/mysite/pie/</code></td>
275
<td><code>/pie/</code></td>
279
<td><code>http://example.com/mysite/ice-cream/yum.html</code></td>
280
<td><code>/mysite/ice-cream/yum.html</code></td>
281
<td><code>/ice-cream/yum.html</code></td>
286
<h3 id="extending-ycontroller">Extending <code>Y.Controller</code></h3>
289
While <code>Y.Controller</code> may be instantiated and used directly, you might find it more convenient to extend the <code>Y.Controller</code> class to create a subclass customized for your particular needs.
293
Use the <code>Y.Base.create()</code> method to extend <code>Y.Controller</code> and add or override prototype and static members. You may also optionally specify one or more <a href="../base/index.html#extensions">Base extensions</a> to mix into your new class.
296
<pre class="code prettyprint">// Create a Y.CustomController class that extends Y.Controller.
297
Y.CustomController = Y.Base.create('customController', Y.Controller, [], {
298
// Add or override prototype properties and methods here.
300
// Add static properties and methods here.
305
One benefit of extending <code>Y.Controller</code> is that you can easily add default config properties, routes, and route handlers to the prototype of your custom Controller class, and they'll be shared by all instances of that class unless overridden at the instance level:
308
<pre class="code prettyprint">Y.CustomController = Y.Base.create('customController', Y.Controller, [], {
309
// Evaluate all routes relative to this root path.
310
root: '/mysite',
312
// Share these default routes with all CustomController instances.
314
{path: '/', callback: 'index'},
315
{path: '/pie', callback: 'pie'}
318
// Default route handlers inherited by all CustomController instances.
319
index: function (req) {
320
// ... handle the / route ...
323
pie: function (req) {
324
// ... handle the /pie route ...
328
// Create a CustomController instance that inherits the defaults and adds to
330
var controller = new Y.CustomController();
332
controller.route('/cheesecake', function (req) {
333
// ... handle the /cheesecake route
338
Now all instances of <code>Y.CustomController</code> will inherit all the custom defaults and can add to or override them. The <code>controller</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.
341
<h3 id="routing">Routing</h3>
344
Use the <code>route()</code> method to add a new route to a Controller 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.
347
<pre class="code prettyprint">var controller = new Y.Controller();
349
// Add a route using a string as the path specification.
350
controller.route('/pie', function () {
351
Y.log('You visited http://example.com/pie');
354
// Add a route using a regular expression as the path specification.
355
controller.route(/^\/cake$/, function () {
356
Y.log('You visited http://example.com/cake');
361
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.
365
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 Controller instance.
368
<pre class="code prettyprint">var controller = new Y.Controller();
370
controller.pie = function () {
371
Y.log('You visited http://example.com/pie');
374
// Add a route using controller.pie as the route callback.
375
controller.route('/pie', 'pie');</pre>
379
As an alternative to using the <code>route()</code> method, routes may be added at instantiation time using the <code>routes</code> config property:
382
<pre class="code prettyprint">var controller = new Y.Controller({
384
{path: '/pie', callback: function () {
385
Y.log('You visited http://example.com/pie');
388
{path: /^\/cake$/, callback: function () {
389
Y.log('You visited http://example.com/cake');
396
This is functionally equivalent to adding the routes via the <code>route()</code> method, except that the routes are added during the Controller's initialization stage rather than after.
399
<h4 id="paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</h4>
402
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.
406
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.
410
A placeholder prefixed by a <code>:</code>, like <code>:pie</code>, will match any character except for a path separator (<code>/</code>).
413
<pre class="code prettyprint">controller.route('/pie/:type/:slices', function (req) {
414
Y.log("You ordered " + req.params.slices + " slices of "
415
+ req.params.type + " pie.");
418
controller.save('/pie/apple/2');
419
// => "You ordered 2 slices of apple pie."
421
controller.save('/pie/lemon+meringue/42');
422
// => "You ordered 42 slices of lemon meringue pie."</pre>
426
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.
429
<pre class="code prettyprint">controller.route('/files/*path', function (req) {
430
Y.log("You requested the file " + req.params.path);
433
controller.save('/files/recipes/pie/pecan.html');
434
// => "You requested the file recipes/pie/pecan.html"</pre>
438
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).
442
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).
445
<pre class="code prettyprint">controller.route(/^\/pie\/([^\/]*)\/([^\/]*)$/, function (req) {
446
Y.log("You ordered " + req.params[1] + " slices of "
447
+ req.params[2] + " pie.");
450
controller.save('/pie/maple+custard/infinity');
451
// => "You ordered infinity slices of maple custard pie."</pre>
454
<h4 id="route-callbacks">Route Callbacks</h4>
457
When a route is matched, the callback function associated with that route will be executed, and will receive two parameters:
461
<dt><strong><code>req</code> (Object)</strong></dt>
464
An object that contains information about the request that triggered the route. It contains the following properties:
468
<dt><strong><code>params</code> (Object or Array)</strong></dt>
471
Parameters matched by the route path specification.
475
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.
479
<dt><strong><code>path</code> (String)</strong></dt>
482
The current URL path matched by the route.
486
<dt><strong><code>query</code> (Object)</strong></dt>
489
Hash of query string parameters and values specified in the URL, if any.
495
<dt><strong><code>next</code> (Function)</strong></dt>
498
A function that will pass control to the next matching route (if any) when called. If not called, no further routes will be executed.
504
Inside a route callback, the <code>this</code> keyword will always refer to the Controller instance that executed that route.
507
<h4 id="chaining-routes">Chaining Routes</h4>
510
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 second parameter. Calling this function will execute the next matching route if there is one.
513
<pre class="code prettyprint">controller.route('/pie', function (req, next) {
514
Y.log('Callback #1 executed!');
518
controller.route('/pie', function (req) {
519
Y.log('Callback #2 executed!');
522
controller.route('/pie', function (req) {
523
Y.log('Callback #3 executed!');
526
controller.save('/pie');
527
// => "Callback #1 executed!"
528
// => "Callback #2 executed!"</pre>
532
If you want the first route callback to pass some data along to subsequent callbacks, you can attach that data to the <code>req</code> object, which is shared between all routes that are executed during a single request.
535
<pre class="code prettyprint">controller.route('/ice-cream', function (req, next) {
536
req.flavor = 'cookie dough';
540
controller.route('/ice-cream', function (req) {
541
Y.log("I sure do like " + req.flavor + " ice cream.");
544
controller.save('/ice-cream');
545
// => "I sure do like cookie dough ice cream."</pre>
548
<h3 id="updating-the-url">Updating the URL</h3>
551
Call the <code>save()</code> or <code>replace()</code> methods to update the URL and store an entry in the browser's history.
555
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.
558
<pre class="code prettyprint">// Save a new history entry.
559
controller.save('/cake');
561
// Replace the current history entry with a new one.
562
controller.replace('/pie');</pre>
566
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.
570
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.
573
<pre class="code prettyprint">controller.route('/ice-cream', function (req) {
574
var flavor = req.query.flavor;
576
if (flavor === 'vanilla') {
577
Y.log('Vanilla? How boring.');
578
} else if (flavor === 'americone dream') {
579
Y.log('Mmmm, Colbert-flavored ice cream.');
581
Y.log('Error! Error! Does not compute!');
585
controller.save('/ice-cream?flavor=vanilla');
586
// => "Vanilla? How boring."
588
controller.save('/ice-cream?flavor=americone+dream');
589
// => "Mmm, Colbert-flavored ice cream."
591
controller.save('/ice-cream?flavor=kitten');
592
// => "Error! Error! Does not compute!"</pre>
595
<h4 id="capturing-link-clicks">Capturing Link Clicks</h4>
598
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.
601
<pre class="code prettyprint">// This sample requires the `node-event-delegate` module.
602
YUI().use('controller', 'node-event-delegate', function (Y) {
603
// ... create a controller instance as described in the sections above ...
605
// Attach a delegated click handler to listen for clicks on all links on the
607
Y.one('body').delegate('click', function (e) {
608
// Allow the native behavior on middle/right-click, or when Ctrl or Command
609
// are pressed.
610
if (e.button !== 1 || e.ctrlKey || e.metaKey) {
614
// Remove the non-path portion of the URL, and any portion of the path that
615
// isn't relative to this controller's root path.
616
var path = controller.removeRoot(e.currentTarget.get('href'));
618
// If the controller has a route that matches this path, then use the
619
// controller to update the URL and handle the route. Otherwise, let the
620
// browser handle the click normally.
621
if (controller.hasRoute(path)) {
623
controller.save(path);
630
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 controller 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.
633
<h3 id="to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</h3>
636
Dispatching is what it's called when Controller looks for routes that match the current URL and then executes the callback of the first matching route (if any).
640
A dispatch can be triggered in the following ways:
644
<li>Automatically, whenever the URL changes after the initial pageview.</li>
645
<li>Manually, by calling the <code>dispatch()</code> method.</li>
646
<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>
650
It's important to remember that if a user bookmarks or copies an HTML5 URL generated by Controller 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.
654
For instance, let's say a user visits your website at <code>http://example.com/</code>. On that page, you have the following code:
657
<pre class="code prettyprint"><button id="pie">Click me if you like pie!</button>
660
YUI().use('controller', 'node', function (Y) {
661
var controller = new Y.Controller();
663
controller.route('/pie', function () {
664
// Show the user a photo of a delicious pie.
667
Y.one('#pie').on('click', function () {
668
controller.save('/pie');
671
</script></pre>
675
In an HTML5 browser, when the user clicks the button, Controller 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.
679
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.
683
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:
686
<pre class="code prettyprint">// Always dispatch to an initial route on legacy browsers. Only dispatch to an
687
// initial route on HTML5 browsers if it's necessary in order to upgrade a
688
// legacy hash URL to an HTML5 URL.
689
if (controller.html5) {
690
controller.upgrade();
692
controller.dispatch();
697
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.
701
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:
704
<pre class="code prettyprint">// Dispatch to an initial route on all browsers.
705
controller.dispatch();</pre>
709
On the one hand, this solution avoids most of the server-side complexity and keeps all the controller 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.
712
<h2 id="best-practices">Best Practices</h2>
714
<h3 id="html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</h3>
717
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.
721
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.
725
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.
729
In general, the benefits of HTML5 URLs tend to outweigh the drawbacks when compared to hash-based URLs, which is why Controller automatically defaults to using HTML5 URLs in browsers that support it. The hash-based URLs generated by Controller should be used only as a fallback for legacy browsers.
732
<h3 id="cross-browser-url-compatibility">Cross-browser URL Compatibility</h3>
735
It's very important that any URL generated by Controller 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.
739
When a hash-based URL is loaded in an HTML5 browser and <code>dispatch()</code> or <code>upgrade()</code> are called, Controller 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.
743
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.
747
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:
751
<li><p>If the server is capable of handling the URL, then it should render the page in the appropriate state, and Controller won't need to do anything.</p></li>
752
<li><p>If the server is not capable of handling the URL, then it should render the initial page state and you should call Controller's <code>dispatch()</code> method. Controller will parse the HTML5 URL and execute the appropriate route, even in a legacy browser.</p></li>
756
For more on how dispatching works, see <a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>.
759
<h3 id="progressive-enhancement-and-seo">Progressive Enhancement and SEO</h3>
762
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).
766
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.
770
Controller'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.
773
<h4 id="supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</h4>
776
One of the problems with the hash-based URLs Controller 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.
780
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.
784
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 Controller do this automatically by setting the value of the static <code>Y.HistoryHash.hashPrefix</code> property before initializing any Controller instances:
787
<pre class="code prettyprint">Y.HistoryHash.hashPrefix = '!';</pre>
791
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.
795
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.
798
<h2 id="known-limitations">Known Limitations</h2>
801
<li><p><strong>HTML5 history is not currently supported by any version of Internet Explorer.</strong> This includes Internet Explorer 9 and developer preview releases of IE10 as of the time these docs were written. Please feel free to let Microsoft know how you feel about this.</p></li>
803
<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>
805
<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>
807
<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>
809
<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>
814
<div id="sidebar" class="yui3-u">
816
<div id="toc" class="sidebox">
818
<h2 class="no-toc">Table of Contents</h2>
824
<a href="#getting-started">Getting Started</a>
827
<a href="#url-based-routing-on-the-client">URL-based Routing on the Client?</a>
830
<a href="#sample-urls">Sample URLs</a>
833
<a href="#using-controller">Using Controller</a>
836
<a href="#instantiating-controller">Instantiating Controller</a>
839
<a href="#config-properties">Config Properties</a>
842
<a href="#read-only-properties">Read-Only Properties</a>
845
<a href="#setting-the-root-path">Setting the Root Path</a>
850
<a href="#extending-ycontroller">Extending <code>Y.Controller</code></a>
853
<a href="#routing">Routing</a>
856
<a href="#paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</a>
859
<a href="#route-callbacks">Route Callbacks</a>
862
<a href="#chaining-routes">Chaining Routes</a>
867
<a href="#updating-the-url">Updating the URL</a>
870
<a href="#capturing-link-clicks">Capturing Link Clicks</a>
875
<a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>
880
<a href="#best-practices">Best Practices</a>
883
<a href="#html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</a>
886
<a href="#cross-browser-url-compatibility">Cross-browser URL Compatibility</a>
889
<a href="#progressive-enhancement-and-seo">Progressive Enhancement and SEO</a>
892
<a href="#supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</a>
899
<a href="#known-limitations">Known Limitations</a>
913
<script src="../assets/vendor/prettify/prettify-min.js"></script>
914
<script>prettyPrint();</script>