UNPKG

32.5 kBMarkdownView Raw
1# Turbolinks
2
3**Turbolinks® makes navigating your web application faster.** Get the performance benefits of a single-page application without the added complexity of a client-side JavaScript framework. Use HTML to render your views on the server side and link to pages as usual. When you follow a link, Turbolinks automatically fetches the page, swaps in its `<body>`, and merges its `<head>`, all without incurring the cost of a full page load.
4
5![Turbolinks](https://s3.amazonaws.com/turbolinks-docs/images/turbolinks.gif)
6
7## Features
8
9- **Optimizes navigation automatically.** No need to annotate links or specify which parts of the page should change.
10- **No server-side cooperation necessary.** Respond with full HTML pages, not partial page fragments or JSON.
11- **Respects the web.** The Back and Reload buttons work just as you’d expect. Search engine-friendly by design.
12- **Supports mobile apps.** Adapters for [iOS](https://github.com/turbolinks/turbolinks-ios) and [Android](https://github.com/turbolinks/turbolinks-android) let you build hybrid applications using native navigation controls.
13
14## Supported Browsers
15
16Turbolinks works in all modern desktop and mobile browsers. It depends on the [HTML5 History API](http://caniuse.com/#search=pushState) and [Window.requestAnimationFrame](http://caniuse.com/#search=requestAnimationFrame). In unsupported browsers, Turbolinks gracefully degrades to standard navigation.
17
18## Installation
19
20Include [`dist/turbolinks.js`](dist/turbolinks.js) in your application’s JavaScript bundle.
21
22Turbolinks automatically initializes itself when loaded via a standalone `<script>` tag or a traditional concatenated JavaScript bundle. If you load Turbolinks as a CommonJS or AMD module, first require the module, then call the provided `start()` function.
23
24### Installation Using Ruby on Rails
25
26Your Ruby on Rails application can use the [`turbolinks` RubyGem](https://github.com/turbolinks/turbolinks-rails) to install Turbolinks. This gem contains a Rails engine which integrates seamlessly with the Rails asset pipeline.
27
281. Add the `turbolinks` gem, version 5, to your Gemfile: `gem 'turbolinks', '~> 5.1.0'`
292. Run `bundle install`.
303. Add `//= require turbolinks` to your JavaScript manifest file (usually found at `app/assets/javascripts/application.js`).
31
32The gem also provides server-side support for Turbolinks redirection, which can be used without the asset pipeline.
33
34### Installation Using npm
35
36Your application can use the [`turbolinks` npm package](https://www.npmjs.com/package/turbolinks) to install Turbolinks as a module for build tools like [webpack](http://webpack.github.io/).
37
381. Add the `turbolinks` package to your application: `npm install --save turbolinks`.
392. Require and start Turbolinks in your JavaScript bundle:
40
41 ```js
42 var Turbolinks = require("turbolinks")
43 Turbolinks.start()
44 ```
45
46#### Table of Contents
47
48[Navigating with Turbolinks](#navigating-with-turbolinks)
49- [Each Navigation is a Visit](#each-navigation-is-a-visit)
50- [Application Visits](#application-visits)
51- [Restoration Visits](#restoration-visits)
52- [Canceling Visits Before They Start](#canceling-visits-before-they-start)
53- [Disabling Turbolinks on Specific Links](#disabling-turbolinks-on-specific-links)
54
55[Building Your Turbolinks Application](#building-your-turbolinks-application)
56- [Working with Script Elements](#working-with-script-elements)
57 - [Loading Your Application’s JavaScript Bundle](#loading-your-applications-javascript-bundle)
58- [Understanding Caching](#understanding-caching)
59 - [Preparing the Page to be Cached](#preparing-the-page-to-be-cached)
60 - [Detecting When a Preview is Visible](#detecting-when-a-preview-is-visible)
61 - [Opting Out of Caching](#opting-out-of-caching)
62- [Installing JavaScript Behavior](#installing-javascript-behavior)
63 - [Observing Navigation Events](#observing-navigation-events)
64 - [Attaching Behavior With Stimulus](#attaching-behavior-with-stimulus)
65- [Making Transformations Idempotent](#making-transformations-idempotent)
66- [Persisting Elements Across Page Loads](#persisting-elements-across-page-loads)
67
68[Advanced Usage](#advanced-usage)
69- [Displaying Progress](#displaying-progress)
70- [Reloading When Assets Change](#reloading-when-assets-change)
71- [Ensuring Specific Pages Trigger a Full Reload](#ensuring-specific-pages-trigger-a-full-reload)
72- [Setting a Root Location](#setting-a-root-location)
73- [Following Redirects](#following-redirects)
74- [Redirecting After a Form Submission](#redirecting-after-a-form-submission)
75- [Setting Custom HTTP Headers](#setting-custom-http-headers)
76
77[API Reference](#api-reference)
78- [Turbolinks.visit](#turbolinksvisit)
79- [Turbolinks.clearCache](#turbolinksclearcache)
80- [Turbolinks.setProgressBarDelay](#turbolinkssetprogressbardelay)
81- [Turbolinks.supported](#turbolinkssupported)
82- [Full List of Events](#full-list-of-events)
83
84[Contributing to Turbolinks](#contributing-to-turbolinks)
85- [Building From Source](#building-from-source)
86- [Running Tests](#running-tests)
87
88# Navigating with Turbolinks
89
90Turbolinks intercepts all clicks on `<a href>` links to the same domain. When you click an eligible link, Turbolinks prevents the browser from following it. Instead, Turbolinks changes the browser’s URL using the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History), requests the new page using [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), and then renders the HTML response.
91
92During rendering, Turbolinks replaces the current `<body>` element outright and merges the contents of the `<head>` element. The JavaScript `window` and `document` objects, and the HTML `<html>` element, persist from one rendering to the next.
93
94## Each Navigation is a Visit
95
96Turbolinks models navigation as a *visit* to a *location* (URL) with an *action*.
97
98Visits represent the entire navigation lifecycle from click to render. That includes changing browser history, issuing the network request, restoring a copy of the page from cache, rendering the final response, and updating the scroll position.
99
100There are two types of visit: an _application visit_, which has an action of _advance_ or _replace_, and a _restoration visit_, which has an action of _restore_.
101
102## Application Visits
103
104Application visits are initiated by clicking a Turbolinks-enabled link, or programmatically by calling [`Turbolinks.visit(location)`](#turbolinksvisit).
105
106An application visit always issues a network request. When the response arrives, Turbolinks renders its HTML and completes the visit.
107
108If possible, Turbolinks will render a preview of the page from cache immediately after the visit starts. This improves the perceived speed of frequent navigation between the same pages.
109
110If the visit’s location includes an anchor, Turbolinks will attempt to scroll to the anchored element. Otherwise, it will scroll to the top of the page.
111
112Application visits result in a change to the browser’s history; the visit’s _action_ determines how.
113
114![Advance visit action](https://s3.amazonaws.com/turbolinks-docs/images/advance.svg)
115
116The default visit action is _advance_. During an advance visit, Turbolinks pushes a new entry onto the browser’s history stack using [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState).
117
118Applications using the Turbolinks [iOS adapter](https://github.com/turbolinks/turbolinks-ios) typically handle advance visits by pushing a new view controller onto the navigation stack. Similarly, applications using the [Android adapter](https://github.com/turbolinks/turbolinks-android) typically push a new activity onto the back stack.
119
120![Replace visit action](https://s3.amazonaws.com/turbolinks-docs/images/replace.svg)
121
122You may wish to visit a location without pushing a new history entry onto the stack. The _replace_ visit action uses [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) to discard the topmost history entry and replace it with the new location.
123
124To specify that following a link should trigger a replace visit, annotate the link with `data-turbolinks-action="replace"`:
125
126```html
127<a href="/edit" data-turbolinks-action="replace">Edit</a>
128```
129
130To programmatically visit a location with the replace action, pass the `action: "replace"` option to [`Turbolinks.visit`](#turbolinksvisit):
131
132```js
133Turbolinks.visit("/edit", { action: "replace" })
134```
135
136Applications using the Turbolinks [iOS adapter](https://github.com/turbolinks/turbolinks-ios) typically handle replace visits by dismissing the topmost view controller and pushing a new view controller onto the navigation stack without animation.
137
138## Restoration Visits
139
140Turbolinks automatically initiates a restoration visit when you navigate with the browser’s Back or Forward buttons. Applications using the [iOS](https://github.com/turbolinks/turbolinks-ios) or [Android](https://github.com/turbolinks/turbolinks-android) adapters initiate a restoration visit when moving backward in the navigation stack.
141
142![Restore visit action](https://s3.amazonaws.com/turbolinks-docs/images/restore.svg)
143
144If possible, Turbolinks will render a copy of the page from cache without making a request. Otherwise, it will retrieve a fresh copy of the page over the network. See [Understanding Caching](#understanding-caching) for more details.
145
146Turbolinks saves the scroll position of each page before navigating away and automatically returns to this saved position on restoration visits.
147
148Restoration visits have an action of _restore_ and Turbolinks reserves them for internal use. You should not attempt to annotate links or invoke [`Turbolinks.visit`](#turbolinksvisit) with an action of `restore`.
149
150## Canceling Visits Before They Start
151
152Application visits can be canceled before they start, regardless of whether they were initiated by a link click or a call to [`Turbolinks.visit`](#turbolinksvisit).
153
154Listen for the `turbolinks:before-visit` event to be notified when a visit is about to start, and use `event.data.url` (or `$event.originalEvent.data.url`, when using jQuery) to check the visit’s location. Then cancel the visit by calling `event.preventDefault()`.
155
156Restoration visits cannot be canceled and do not fire `turbolinks:before-visit`. Turbolinks issues restoration visits in response to history navigation that has *already taken place*, typically via the browser’s Back or Forward buttons.
157
158## Disabling Turbolinks on Specific Links
159
160Turbolinks can be disabled on a per-link basis by annotating a link or any of its ancestors with `data-turbolinks="false"`.
161
162```html
163<a href="/" data-turbolinks="false">Disabled</a>
164
165<div data-turbolinks="false">
166 <a href="/">Disabled</a>
167</div>
168```
169
170To reenable when an ancestor has opted out, use `data-turbolinks="true"`:
171
172```html
173<div data-turbolinks="false">
174 <a href="/" data-turbolinks="true">Enabled</a>
175</div>
176```
177
178Links with Turbolinks disabled will be handled normally by the browser.
179
180# Building Your Turbolinks Application
181
182Turbolinks is fast because it doesn’t reload the page when you follow a link. Instead, your application becomes a persistent, long-running process in the browser. This requires you to rethink the way you structure your JavaScript.
183
184In particular, you can no longer depend on a full page load to reset your environment every time you navigate. The JavaScript `window` and `document` objects retain their state across page changes, and any other objects you leave in memory will stay in memory.
185
186With awareness and a little extra care, you can design your application to gracefully handle this constraint without tightly coupling it to Turbolinks.
187
188## Working with Script Elements
189
190Your browser automatically loads and evaluates any `<script>` elements present on the initial page load.
191
192When you navigate to a new page, Turbolinks looks for any `<script>` elements in the new page’s `<head>` which aren’t present on the current page. Then it appends them to the current `<head>` where they’re loaded and evaluated by the browser. You can use this to load additional JavaScript files on-demand.
193
194Turbolinks evaluates `<script>` elements in a page’s `<body>` each time it renders the page. You can use inline body scripts to set up per-page JavaScript state or bootstrap client-side models. To install behavior, or to perform more complex operations when the page changes, avoid script elements and use the `turbolinks:load` event instead.
195
196Annotate `<script>` elements with `data-turbolinks-eval="false"` if you do not want Turbolinks to evaluate them after rendering. Note that this annotation will not prevent your browser from evaluating scripts on the initial page load.
197
198### Loading Your Application’s JavaScript Bundle
199
200Always make sure to load your application’s JavaScript bundle using `<script>` elements in the `<head>` of your document. Otherwise, Turbolinks will reload the bundle with every page change.
201
202```html
203<head>
204 ...
205 <script src="/application-cbd3cd4.js" defer></script>
206</head>
207```
208
209If you have traditionally placed application scripts at the end of `<body>` for performance reasons, consider using the [`<script defer>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer) attribute instead. It has [widespread browser support](https://caniuse.com/#feat=script-defer) and allows you to keep your scripts in `<head>` for Turbolinks compatibility.
210
211You should also consider configuring your asset packaging system to fingerprint each script so it has a new URL when its contents change. Then you can use the `data-turbolinks-track` attribute to force a full page reload when you deploy a new JavaScript bundle. See [Reloading When Assets Change](#reloading-when-assets-change) for information.
212
213## Understanding Caching
214
215Turbolinks maintains a cache of recently visited pages. This cache serves two purposes: to display pages without accessing the network during restoration visits, and to improve perceived performance by showing temporary previews during application visits.
216
217When navigating by history (via [Restoration Visits](#restoration-visits)), Turbolinks will restore the page from cache without loading a fresh copy from the network, if possible.
218
219Otherwise, during standard navigation (via [Application Visits](#application-visits)), Turbolinks will immediately restore the page from cache and display it as a preview while simultaneously loading a fresh copy from the network. This gives the illusion of instantaneous page loads for frequently accessed locations.
220
221Turbolinks saves a copy of the current page to its cache just before rendering a new page. Note that Turbolinks copies the page using [`cloneNode(true)`](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode), which means any attached event listeners and associated data are discarded.
222
223### Preparing the Page to be Cached
224
225Listen for the `turbolinks:before-cache` event if you need to prepare the document before Turbolinks caches it. You can use this event to reset forms, collapse expanded UI elements, or tear down any third-party widgets so the page is ready to be displayed again.
226
227```js
228document.addEventListener("turbolinks:before-cache", function() {
229 // ...
230})
231```
232
233### Detecting When a Preview is Visible
234
235Turbolinks adds a `data-turbolinks-preview` attribute to the `<html>` element when it displays a preview from cache. You can check for the presence of this attribute to selectively enable or disable behavior when a preview is visible.
236
237```js
238if (document.documentElement.hasAttribute("data-turbolinks-preview")) {
239 // Turbolinks is displaying a preview
240}
241```
242
243### Opting Out of Caching
244
245You can control caching behavior on a per-page basis by including a `<meta name="turbolinks-cache-control">` element in your page’s `<head>` and declaring a caching directive.
246
247Use the `no-preview` directive to specify that a cached version of the page should not be shown as a preview during an application visit. Pages marked no-preview will only be used for restoration visits.
248
249To specify that a page should not be cached at all, use the `no-cache` directive. Pages marked no-cache will always be fetched over the network, including during restoration visits.
250
251```html
252<head>
253 ...
254 <meta name="turbolinks-cache-control" content="no-cache">
255</head>
256```
257
258To completely disable caching in your application, ensure every page contains a no-cache directive.
259
260## Installing JavaScript Behavior
261
262You may be used to installing JavaScript behavior in response to the `window.onload`, `DOMContentLoaded`, or jQuery `ready` events. With Turbolinks, these events will fire only in response to the initial page load, not after any subsequent page changes. We compare two strategies for connecting JavaScript behavior to the DOM below.
263
264### Observing Navigation Events
265
266Turbolinks triggers a series of events during navigation. The most significant of these is the `turbolinks:load` event, which fires once on the initial page load, and again after every Turbolinks visit.
267
268You can observe the `turbolinks:load` event in place of `DOMContentLoaded` to set up JavaScript behavior after every page change:
269
270```js
271document.addEventListener("turbolinks:load", function() {
272 // ...
273})
274```
275
276Keep in mind that your application will not always be in a pristine state when this event is fired, and you may need to clean up behavior installed for the previous page.
277
278Also note that Turbolinks navigation may not be the only source of page updates in your application, so you may wish to move your initialization code into a separate function which you can call from `turbolinks:load` and anywhere else you may change the DOM.
279
280When possible, avoid using the `turbolinks:load` event to add other event listeners directly to elements on the page body. Instead, consider using [event delegation](https://learn.jquery.com/events/event-delegation/) to register event listeners once on `document` or `window`.
281
282See the [Full List of Events](#full-list-of-events) for more information.
283
284### Attaching Behavior With Stimulus
285
286New DOM elements can appear on the page at any time by way of Ajax request handlers, WebSocket handlers, or client-side rendering operations, and these elements often need to be initialized as if they came from a fresh page load.
287
288You can handle all of these updates, including updates from Turbolinks page loads, in a single place with the conventions and lifecycle callbacks provided by Turbolinks’ sister framework, [Stimulus](https://github.com/stimulusjs/stimulus).
289
290Stimulus lets you annotate your HTML with controller, action, and target attributes:
291
292```html
293<div data-controller="hello">
294 <input data-target="hello.name" type="text">
295 <button data-action="click->hello#greet">Greet</button>
296</div>
297```
298
299Implement a compatible controller and Stimulus connects it automatically:
300
301```js
302// hello_controller.js
303import { Controller } from "stimulus"
304
305export default class extends Controller {
306 greet() {
307 console.log(`Hello, ${this.name}!`)
308 }
309
310 get name() {
311 return this.targets.find("name").value
312 }
313}
314```
315
316Stimulus connects and disconnects these controllers and their associated event handlers whenever the document changes using the [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) API. As a result, it handles Turbolinks page changes the same way it handles any other type of DOM update.
317
318See the [Stimulus repository on GitHub](https://github.com/stimulusjs/stimulus) for more information.
319
320## Making Transformations Idempotent
321
322Often you’ll want to perform client-side transformations to HTML received from the server. For example, you might want to use the browser’s knowledge of the user’s current time zone to group a collection of elements by date.
323
324Suppose you have annotated a set of elements with `data-timestamp` attributes indicating the elements’ creation times in UTC. You have a JavaScript function that queries the document for all such elements, converts the timestamps to local time, and inserts date headers before each element that occurs on a new day.
325
326Consider what happens if you’ve configured this function to run on `turbolinks:load`. When you navigate to the page, your function inserts date headers. Navigate away, and Turbolinks saves a copy of the transformed page to its cache. Now press the Back button—Turbolinks restores the page, fires `turbolinks:load` again, and your function inserts a second set of date headers.
327
328To avoid this problem, make your transformation function _idempotent_. An idempotent transformation is safe to apply multiple times without changing the result beyond its initial application.
329
330One technique for making a transformation idempotent is to keep track of whether you’ve already performed it by setting a `data` attribute on each processed element. When Turbolinks restores your page from cache, these attributes will still be present. Detect these attributes in your transformation function to determine which elements have already been processed.
331
332A more robust technique is simply to detect the transformation itself. In the date grouping example above, that means checking for the presence of a date divider before inserting a new one. This approach gracefully handles newly inserted elements that weren’t processed by the original transformation.
333
334## Persisting Elements Across Page Loads
335
336Turbolinks allows you to mark certain elements as _permanent_. Permanent elements persist across page loads, so that any changes you make to those elements do not need to be reapplied after navigation.
337
338Consider a Turbolinks application with a shopping cart. At the top of each page is an icon with the number of items currently in the cart. This counter is updated dynamically with JavaScript as items are added and removed.
339
340Now imagine a user who has navigated to several pages in this application. She adds an item to her cart, then presses the Back button in her browser. Upon navigation, Turbolinks restores the previous page’s state from cache, and the cart item count erroneously changes from 1 to 0.
341
342You can avoid this problem by marking the counter element as permanent. Designate permanent elements by giving them an HTML `id` and annotating them with `data-turbolinks-permanent`.
343
344```html
345<div id="cart-counter" data-turbolinks-permanent>1 item</div>
346```
347
348Before each render, Turbolinks matches all permanent elements by `id` and transfers them from the original page to the new page, preserving their data and event listeners.
349
350# Advanced Usage
351
352## Displaying Progress
353
354During Turbolinks navigation, the browser will not display its native progress indicator. Turbolinks installs a CSS-based progress bar to provide feedback while issuing a request.
355
356The progress bar is enabled by default. It appears automatically for any page that takes longer than 500ms to load. (You can change this delay with the [`Turbolinks.setProgressBarDelay`](#turbolinkssetprogressbardelay) method.)
357
358The progress bar is a `<div>` element with the class name `turbolinks-progress-bar`. Its default styles appear first in the document and can be overridden by rules that come later.
359
360For example, the following CSS will result in a thick green progress bar:
361
362```css
363.turbolinks-progress-bar {
364 height: 5px;
365 background-color: green;
366}
367```
368
369To disable the progress bar entirely, set its `visibility` style to `hidden`:
370
371```css
372.turbolinks-progress-bar {
373 visibility: hidden;
374}
375```
376
377## Reloading When Assets Change
378
379Turbolinks can track the URLs of asset elements in `<head>` from one page to the next and automatically issue a full reload if they change. This ensures that users always have the latest versions of your application’s scripts and styles.
380
381Annotate asset elements with `data-turbolinks-track="reload"` and include a version identifier in your asset URLs. The identifier could be a number, a last-modified timestamp, or better, a digest of the asset’s contents, as in the following example.
382
383```html
384<head>
385 ...
386 <link rel="stylesheet" href="/application-258e88d.css" data-turbolinks-track="reload">
387 <script src="/application-cbd3cd4.js" data-turbolinks-track="reload"></script>
388</head>
389```
390
391## Ensuring Specific Pages Trigger a Full Reload
392
393You can ensure visits to a certain page will always trigger a full reload by including a `<meta name="turbolinks-visit-control">` element in the page’s `<head>`.
394
395```html
396<head>
397 ...
398 <meta name="turbolinks-visit-control" content="reload">
399</head>
400```
401
402This setting may be useful as a workaround for third-party JavaScript libraries that don’t interact well with Turbolinks page changes.
403
404## Setting a Root Location
405
406By default, Turbolinks only loads URLs with the same origin—i.e. the same protocol, domain name, and port—as the current document. A visit to any other URL falls back to a full page load.
407
408In some cases, you may want to further scope Turbolinks to a path on the same origin. For example, if your Turbolinks application lives at `/app`, and the non-Turbolinks help site lives at `/help`, links from the app to the help site shouldn’t use Turbolinks.
409
410Include a `<meta name="turbolinks-root">` element in your pages’ `<head>` to scope Turbolinks to a particular root location. Turbolinks will only load same-origin URLs that are prefixed with this path.
411
412```html
413<head>
414 ...
415 <meta name="turbolinks-root" content="/app">
416</head>
417```
418
419## Following Redirects
420
421When you visit location `/one` and the server redirects you to location `/two`, you expect the browser’s address bar to display the redirected URL.
422
423However, Turbolinks makes requests using `XMLHttpRequest`, which transparently follows redirects. There’s no way for Turbolinks to tell whether a request resulted in a redirect without additional cooperation from the server.
424
425To work around this problem, send the `Turbolinks-Location` header in response to a visit that was redirected, and Turbolinks will replace the browser’s topmost history entry with the value you provide.
426
427The Turbolinks Rails engine sets `Turbolinks-Location` automatically when using `redirect_to` in response to a Turbolinks visit.
428
429## Redirecting After a Form Submission
430
431Submitting an HTML form to the server and redirecting in response is a common pattern in web applications. Standard form submission is similar to navigation, resulting in a full page load. Using Turbolinks you can improve the performance of form submission without complicating your server-side code.
432
433Instead of submitting forms normally, submit them with XHR. In response to an XHR submit on the server, return JavaScript that performs a [`Turbolinks.visit`](#turbolinksvisit) to be evaluated by the browser.
434
435If form submission results in a state change on the server that affects cached pages, consider clearing Turbolinks’ cache with [`Turbolinks.clearCache()`](#turbolinksclearcache).
436
437The Turbolinks Rails engine performs this optimization automatically for non-GET XHR requests that redirect with the `redirect_to` helper.
438
439## Setting Custom HTTP Headers
440
441You can observe the `turbolinks:request-start` event to set custom headers on Turbolinks requests. Access the request’s XMLHttpRequest object via `event.data.xhr`, then call the [`setRequestHeader`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) method as many times as you wish.
442
443For example, you might want to include a request ID with every Turbolinks link click and programmatic visit.
444
445```javascript
446document.addEventListener("turbolinks:request-start", function(event) {
447 var xhr = event.data.xhr
448 xhr.setRequestHeader("X-Request-Id", "123...")
449})
450```
451
452# API Reference
453
454## Turbolinks.visit
455
456Usage:
457```js
458Turbolinks.visit(location)
459Turbolinks.visit(location, { action: action })
460```
461
462Performs an [Application Visit](#application-visits) to the given _location_ (a string containing a URL or path) with the specified _action_ (a string, either `"advance"` or `"replace"`).
463
464If _location_ is a cross-origin URL, or falls outside of the specified root (see [Setting a Root Location](#setting-a-root-location)), or if the value of [`Turbolinks.supported`](#turbolinkssupported) is `false`, Turbolinks performs a full page load by setting `window.location`.
465
466If _action_ is unspecified, Turbolinks assumes a value of `"advance"`.
467
468Before performing the visit, Turbolinks fires a `turbolinks:before-visit` event on `document`. Your application can listen for this event and cancel the visit with `event.preventDefault()` (see [Canceling Visits Before They Start](#canceling-visits-before-they-start)).
469
470## Turbolinks.clearCache
471
472Usage:
473```js
474Turbolinks.clearCache()
475```
476
477Removes all entries from the Turbolinks page cache. Call this when state has changed on the server that may affect cached pages.
478
479## Turbolinks.setProgressBarDelay
480
481Usage:
482```js
483Turbolinks.setProgressBarDelay(delayInMilliseconds)
484```
485
486Sets the delay after which the [progress bar](#displaying-progress) will appear during navigation, in milliseconds. The progress bar appears after 500ms by default.
487
488Note that this method has no effect when used with the iOS or Android adapters.
489
490## Turbolinks.supported
491
492Usage:
493```js
494if (Turbolinks.supported) {
495 // ...
496}
497```
498
499Detects whether Turbolinks is supported in the current browser (see [Supported Browsers](#supported-browsers)).
500
501## Full List of Events
502
503Turbolinks emits events that allow you to track the navigation lifecycle and respond to page loading. Except where noted, Turbolinks fires events on the `document` object.
504
505* `turbolinks:click` fires when you click a Turbolinks-enabled link. The clicked element is the event target. Access the requested location with `event.data.url`. Cancel this event to let the click fall through to the browser as normal navigation.
506
507* `turbolinks:before-visit` fires before visiting a location, except when navigating by history. Access the requested location with `event.data.url`. Cancel this event to prevent navigation.
508
509* `turbolinks:visit` fires immediately after a visit starts.
510
511* `turbolinks:request-start` fires before Turbolinks issues a network request to fetch the page. Access the XMLHttpRequest object with `event.data.xhr`.
512
513* `turbolinks:request-end` fires after the network request completes. Access the XMLHttpRequest object with `event.data.xhr`.
514
515* `turbolinks:before-cache` fires before Turbolinks saves the current page to cache.
516
517* `turbolinks:before-render` fires before rendering the page. Access the new `<body>` element with `event.data.newBody`.
518
519* `turbolinks:render` fires after Turbolinks renders the page. This event fires twice during an application visit to a cached location: once after rendering the cached version, and again after rendering the fresh version.
520
521* `turbolinks:load` fires once after the initial page load, and again after every Turbolinks visit. Access visit timing metrics with the `event.data.timing` object.
522
523# Contributing to Turbolinks
524
525Turbolinks is open-source software, freely distributable under the terms of an [MIT-style license](LICENSE). The [source code is hosted on GitHub](https://github.com/turbolinks/turbolinks).
526Development is sponsored by [Basecamp](https://basecamp.com/).
527
528We welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the [GitHub issue tracker](https://github.com/turbolinks/turbolinks/issues).
529
530Please note that this project is released with a [Contributor Code of Conduct](CONDUCT.md). By participating in this project you agree to abide by its terms.
531
532## Building From Source
533
534Turbolinks is written in [CoffeeScript](https://github.com/jashkenas/coffee-script) and compiled to JavaScript with [Blade](https://github.com/javan/blade). To build from source you’ll need a recent version of Ruby. From the root of your Turbolinks directory, issue the following commands to build the distributable files in `dist/`:
535
536```
537$ gem install bundler
538$ bundle install
539$ bin/blade build
540```
541
542## Running Tests
543
544The Turbolinks test suite is written in [TypeScript](https://www.typescriptlang.org) with the [Intern testing library](https://theintern.io).
545
546To run the tests, first make sure you have the [Yarn package manager](https://yarnpkg.com) installed. Follow the instructions for _Building From Source_ above, then run the following commands:
547
548```
549$ cd test
550$ yarn install
551$ yarn test
552```
553
554If you are testing changes to the Turbolinks source, remember to run `bin/blade build` before each test run.
555
556---
557
558© 2018 Basecamp, LLC.