Turbolinks makes navigating your web application faster

Overview

Turbolinks is no longer under active development

Please note that Turbolinks is no longer under active development. It has been superseded by a new framework called Turbo, which is part of the Hotwire umbrella.

Turbolinks

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.

Turbolinks

Features

  • Optimizes navigation automatically. No need to annotate links or specify which parts of the page should change.
  • No server-side cooperation necessary. Respond with full HTML pages, not partial page fragments or JSON.
  • Respects the web. The Back and Reload buttons work just as you’d expect. Search engine-friendly by design.
  • Supports mobile apps. Adapters for iOS and Android let you build hybrid applications using native navigation controls.

Supported Browsers

Turbolinks works in all modern desktop and mobile browsers. It depends on the HTML5 History API and Window.requestAnimationFrame. In unsupported browsers, Turbolinks gracefully degrades to standard navigation.

Installation

Turbolinks 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.

Installation Using Ruby on Rails

Your Ruby on Rails application can use the turbolinks RubyGem to install Turbolinks. This gem contains a Rails engine which integrates seamlessly with the Rails asset pipeline.

  1. Add the turbolinks gem, version 5, to your Gemfile: gem 'turbolinks', '~> 5.2.0'
  2. Run bundle install.
  3. Add //= require turbolinks to your JavaScript manifest file (usually found at app/assets/javascripts/application.js).

The gem also provides server-side support for Turbolinks redirection, which can be used without the asset pipeline.

Installation Using npm

Your application can use the turbolinks npm package to install Turbolinks as a module for build tools like webpack.

  1. Add the turbolinks package to your application: npm install --save turbolinks.

  2. Require and start Turbolinks in your JavaScript bundle:

    var Turbolinks = require("turbolinks")
    Turbolinks.start()

The npm package alone does not provide server-side support for Turbolinks redirection. See Following Redirects for details on adding support.

Table of Contents

Navigating with Turbolinks

Building Your Turbolinks Application

Advanced Usage

API Reference

Contributing to Turbolinks

Navigating with Turbolinks

Turbolinks 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, requests the new page using XMLHttpRequest, and then renders the HTML response.

During 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.

Each Navigation is a Visit

Turbolinks models navigation as a visit to a location (URL) with an action.

Visits 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.

There 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.

Application Visits

Application visits are initiated by clicking a Turbolinks-enabled link, or programmatically by calling Turbolinks.visit(location).

An application visit always issues a network request. When the response arrives, Turbolinks renders its HTML and completes the visit.

If 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.

If 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.

Application visits result in a change to the browser’s history; the visit’s action determines how.

Advance visit action

The default visit action is advance. During an advance visit, Turbolinks pushes a new entry onto the browser’s history stack using history.pushState.

Applications using the Turbolinks iOS adapter typically handle advance visits by pushing a new view controller onto the navigation stack. Similarly, applications using the Android adapter typically push a new activity onto the back stack.

Replace visit action

You may wish to visit a location without pushing a new history entry onto the stack. The replace visit action uses history.replaceState to discard the topmost history entry and replace it with the new location.

To specify that following a link should trigger a replace visit, annotate the link with data-turbolinks-action="replace":

<a href="/edit" data-turbolinks-action="replace">Edit</a>

To programmatically visit a location with the replace action, pass the action: "replace" option to Turbolinks.visit:

Turbolinks.visit("/edit", { action: "replace" })

Applications using the Turbolinks iOS adapter typically handle replace visits by dismissing the topmost view controller and pushing a new view controller onto the navigation stack without animation.

Restoration Visits

Turbolinks automatically initiates a restoration visit when you navigate with the browser’s Back or Forward buttons. Applications using the iOS or Android adapters initiate a restoration visit when moving backward in the navigation stack.

Restore visit action

If 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 for more details.

Turbolinks saves the scroll position of each page before navigating away and automatically returns to this saved position on restoration visits.

Restoration visits have an action of restore and Turbolinks reserves them for internal use. You should not attempt to annotate links or invoke Turbolinks.visit with an action of restore.

Canceling Visits Before They Start

Application visits can be canceled before they start, regardless of whether they were initiated by a link click or a call to Turbolinks.visit.

Listen 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().

Restoration 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.

Disabling Turbolinks on Specific Links

Turbolinks can be disabled on a per-link basis by annotating a link or any of its ancestors with data-turbolinks="false".

<a href="/" data-turbolinks="false">Disabled</a>

<div data-turbolinks="false">
  <a href="/">Disabled</a>
</div>

To reenable when an ancestor has opted out, use data-turbolinks="true":

<div data-turbolinks="false">
  <a href="/" data-turbolinks="true">Enabled</a>
</div>

Links with Turbolinks disabled will be handled normally by the browser.

Building Your Turbolinks Application

Turbolinks 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.

In 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.

With awareness and a little extra care, you can design your application to gracefully handle this constraint without tightly coupling it to Turbolinks.

Working with Script Elements

Your browser automatically loads and evaluates any <script> elements present on the initial page load.

When 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.

Turbolinks 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.

Annotate <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.

Loading Your Application’s JavaScript Bundle

Always 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.

<head>
  ...
  <script src="/application-cbd3cd4.js" defer></script>
</head>

If you have traditionally placed application scripts at the end of <body> for performance reasons, consider using the <script defer> attribute instead. It has widespread browser support and allows you to keep your scripts in <head> for Turbolinks compatibility.

You 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 for information.

Understanding Caching

Turbolinks 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.

When navigating by history (via Restoration Visits), Turbolinks will restore the page from cache without loading a fresh copy from the network, if possible.

Otherwise, during standard navigation (via 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.

Turbolinks 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), which means any attached event listeners and associated data are discarded.

Preparing the Page to be Cached

Listen 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.

document.addEventListener("turbolinks:before-cache", function() {
  // ...
})

Detecting When a Preview is Visible

Turbolinks 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.

if (document.documentElement.hasAttribute("data-turbolinks-preview")) {
  // Turbolinks is displaying a preview
}

Opting Out of Caching

You 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.

Use 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.

To 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.

<head>
  ...
  <meta name="turbolinks-cache-control" content="no-cache">
</head>

To completely disable caching in your application, ensure every page contains a no-cache directive.

Installing JavaScript Behavior

You 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.

Observing Navigation Events

Turbolinks 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.

You can observe the turbolinks:load event in place of DOMContentLoaded to set up JavaScript behavior after every page change:

document.addEventListener("turbolinks:load", function() {
  // ...
})

Keep 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.

Also 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.

When possible, avoid using the turbolinks:load event to add other event listeners directly to elements on the page body. Instead, consider using event delegation to register event listeners once on document or window.

See the Full List of Events for more information.

Attaching Behavior With Stimulus

New 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.

You 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.

Stimulus lets you annotate your HTML with controller, action, and target attributes:

<div data-controller="hello">
  <input data-target="hello.name" type="text">
  <button data-action="click->hello#greet">Greet</button>
</div>

Implement a compatible controller and Stimulus connects it automatically:

// hello_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  greet() {
    console.log(`Hello, ${this.name}!`)
  }

  get name() {
    return this.targets.find("name").value
  }
}

Stimulus connects and disconnects these controllers and their associated event handlers whenever the document changes using the MutationObserver API. As a result, it handles Turbolinks page changes the same way it handles any other type of DOM update.

See the Stimulus repository on GitHub for more information.

Making Transformations Idempotent

Often 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.

Suppose 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.

Consider 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.

To 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.

One 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.

A 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.

Persisting Elements Across Page Loads

Turbolinks 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.

Consider 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.

Now 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.

You 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.

<div id="cart-counter" data-turbolinks-permanent>1 item</div>

Before 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.

Advanced Usage

Displaying Progress

During 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.

The 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 method.)

The 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.

For example, the following CSS will result in a thick green progress bar:

.turbolinks-progress-bar {
  height: 5px;
  background-color: green;
}

To disable the progress bar entirely, set its visibility style to hidden:

.turbolinks-progress-bar {
  visibility: hidden;
}

Reloading When Assets Change

Turbolinks 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.

Annotate 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.

<head>
  ...
  <link rel="stylesheet" href="/application-258e88d.css" data-turbolinks-track="reload">
  <script src="/application-cbd3cd4.js" data-turbolinks-track="reload"></script>
</head>

Ensuring Specific Pages Trigger a Full Reload

You 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>.

<head>
  ...
  <meta name="turbolinks-visit-control" content="reload">
</head>

This setting may be useful as a workaround for third-party JavaScript libraries that don’t interact well with Turbolinks page changes.

Setting a Root Location

By 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.

In 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.

Include 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.

<head>
  ...
  <meta name="turbolinks-root" content="/app">
</head>

Following Redirects

When you visit location /one and the server redirects you to location /two, you expect the browser’s address bar to display the redirected URL.

However, 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.

To work around this problem, send the Turbolinks-Location header in the final response to a visit that was redirected, and Turbolinks will replace the browser’s topmost history entry with the value you provide.

The Turbolinks Rails engine sets Turbolinks-Location automatically when using redirect_to in response to a Turbolinks visit.

Redirecting After a Form Submission

Submitting 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.

Instead of submitting forms normally, submit them with XHR. In response to an XHR submit on the server, return JavaScript that performs a Turbolinks.visit to be evaluated by the browser.

If form submission results in a state change on the server that affects cached pages, consider clearing Turbolinks’ cache with Turbolinks.clearCache().

The Turbolinks Rails engine performs this optimization automatically for non-GET XHR requests that redirect with the redirect_to helper.

Setting Custom HTTP Headers

You 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 method as many times as you wish.

For example, you might want to include a request ID with every Turbolinks link click and programmatic visit.

document.addEventListener("turbolinks:request-start", function(event) {
  var xhr = event.data.xhr
  xhr.setRequestHeader("X-Request-Id", "123...")
})

API Reference

Turbolinks.visit

Usage:

Turbolinks.visit(location)
Turbolinks.visit(location, { action: action })

Performs an Application Visit to the given location (a string containing a URL or path) with the specified action (a string, either "advance" or "replace").

If location is a cross-origin URL, or falls outside of the specified root (see Setting a Root Location), or if the value of Turbolinks.supported is false, Turbolinks performs a full page load by setting window.location.

If action is unspecified, Turbolinks assumes a value of "advance".

Before 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).

Turbolinks.clearCache

Usage:

Turbolinks.clearCache()

Removes all entries from the Turbolinks page cache. Call this when state has changed on the server that may affect cached pages.

Turbolinks.setProgressBarDelay

Usage:

Turbolinks.setProgressBarDelay(delayInMilliseconds)

Sets the delay after which the progress bar will appear during navigation, in milliseconds. The progress bar appears after 500ms by default.

Note that this method has no effect when used with the iOS or Android adapters.

Turbolinks.supported

Usage:

if (Turbolinks.supported) {
  // ...
}

Detects whether Turbolinks is supported in the current browser (see Supported Browsers).

Full List of Events

Turbolinks 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.
Note that when using jQuery, the data on the event must be accessed as $event.originalEvent.data.

  • 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.

  • 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.

  • turbolinks:visit fires immediately after a visit starts.

  • turbolinks:request-start fires before Turbolinks issues a network request to fetch the page. Access the XMLHttpRequest object with event.data.xhr.

  • turbolinks:request-end fires after the network request completes. Access the XMLHttpRequest object with event.data.xhr.

  • turbolinks:before-cache fires before Turbolinks saves the current page to cache.

  • turbolinks:before-render fires before rendering the page. Access the new <body> element with event.data.newBody.

  • 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.

  • 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.

Contributing to Turbolinks

Turbolinks is open-source software, freely distributable under the terms of an MIT-style license. The source code is hosted on GitHub. Development is sponsored by Basecamp.

We welcome contributions in the form of bug reports, pull requests, or thoughtful discussions in the GitHub issue tracker.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Building From Source

Turbolinks is written in TypeScript. To build from source, first make sure you have the Yarn package manager installed. Then issue the following commands to build the distributable files in dist/:

$ yarn install
$ yarn build

Include the resulting dist/turbolinks.js file in your application’s JavaScript bundle.

Running Tests

Turbolinks is tested with the Intern testing library.

To run the test suite, follow the instructions for Building From Source above, then run:

$ yarn test

If you are testing changes to the Turbolinks source, remember to run yarn build before each test run. Or, run yarn watch to build automatically as you work.


© 2019 Basecamp, LLC.

Comments
  • Turbolinks should follow same-page anchor links without reloading the page

    Turbolinks should follow same-page anchor links without reloading the page

    Consider the following HTML link to an element with an id of bookmark:

    <a href="#bookmark" >Bookmark within page</a>

    Turbolinks currently intercepts this link and prevents the browser from following it unless you add an annotation on the link (data-turbolinks="false"). Once Turbolinks has intercepted the link, it makes another HTTP request for the same location again (but with the id appended at the end (/url#bookmark)) instead of just scrolling to the anchored element. Since bookmark links within the same page normally do not result in an HTTP request, one could argue that the default behavior of Turbolinks for links that have an href attribute beginning with # results in worse performance (due to the network request) and violates the principle of least surprise.

    Is it possible to disable Turbolinks for all links that have an href attribute beginning with # without having to manually annotate them with data-turbolinks="false"?

    I am currently using turbolinks (5.0.0.beta2) (turbolinks-source (5.0.0.beta4)) with Rails 4.2.6.

    bug 
    opened by preetpalS 44
  • Handling form errors with Rails automatically?

    Handling form errors with Rails automatically?

    When you submit a form that has errors, Rails normally renders the new action again with the form and the errors. With Turbolinks as it is setup right now, the redirects are handled nicely, but this piece requires you to build your own create.js.erb response to render the errors.

    Would it make sense to add something into Turbolinks / turbolinks-rails that if you submitted a non-GET request and it returned an HTML response that it would take the URL of the request and navigate to that but render the HTML that was returned from the server?

    opened by excid3 39
  • 5.x: POST to create causes URL change even if form errors occured

    5.x: POST to create causes URL change even if form errors occured

    Running Rails 5.0.0beta3 + TurboLinks 5.x

    When I post a form for "create", and the create action re-renders the "new" action, turbolinks is updating the URL to the POST url.

    If the user then reloads the page, they end up with the index action rather than back at "new"...

    opened by sblackstone 38
  • turbolinks:load fires twice

    turbolinks:load fires twice

    I am experiencing the turbolinks:load event being fired twice on initial load of the page as well as each subsequent request for more content from the backend.

    These are the versions I'm using:

    • gem 'rails', '>= 5.0.0.rc1', '< 5.1'
    • gem 'turbolinks', '~> 5.x'

    I subscribe to this event once in my client side: $(document).on("turbolinks:load", function () { .... I was unable to find anything in the documentation nor on Google search results about this event being fired more than once, so I'm not sure how to proceed fixing this. Does anyone have any methods they could recommend in discovering the cause to this?

    Also, in the call stack below, does it show jQuery invoking the turbolinks:load after Turbolinks itself invokes that event? screenshot from 2016-05-21 23-06-32

    opened by jakehockey10 32
  • Javascript not executing

    Javascript not executing

    After upgrading to Turbolinks 5, the javascript in the new page is no longer executing. (Only the javascript in the original fully loaded page is executing). Has javascript execution in turbolinks 5 changed?

    opened by coffeebite 30
  • If page is interactive, fire pageLoaded() immediately

    If page is interactive, fire pageLoaded() immediately

    When using Turbolinks with the async script attribute, Turbolinks may execute after DOMContentLoaded. To fix this, we only attach a handler to DOMContentLoaded if the readystate is not "loading" (that is to say, it is "interactive" or "complete"). Otherwise, we fire the pageLoaded event immediately without installing the handler.

    This changes Turbolinks interaction with defer scripts. After this change, an async Turbolinks script may execute before defered scripts. This is because the browser executes all defer scripts before the DOMContentLoaded event. Previously, Turbolinks would always execute after these scripts, but may now execute before them in some cases depending on when Turbolinks has finished downloading.

    opened by nateberkopec 24
  • Styles get left in head?

    Styles get left in head?

    When navigating between pages, stylesheets unique to a page, get left in the head. Even with no-cache enabled. Do we have control over what stylesheets / scripts we want to persist and what we want to be freshly loaded, between requests?

    opened by Kiszko 23
  • browser back button causes some scripts to reevaluate

    browser back button causes some scripts to reevaluate

    When I use the browser back button some scripts seem to be re-evaluating each time the button is pressed. For instance if I click a link that takes me from an index view to a show view, if there is a plugin such as jquery dataTables initialized on the index view, when I use the browser back button to go back to the index from the show view scripts will be re-evaluated and will duplicate causing unexpected behavior (e.g. in the case of dataTables the table will be initialized multiple times with dataTables elements appearing for each restoration visit -- note this is not just an issue with dataTables, it's occurring with other plugins). These scripts are in the head and inside of an event listener: document.addEventListener("turbolinks:load", function() {

    opened by jaredgalanis 23
  • Google analytics best practice?

    Google analytics best practice?

    First off, absolutely loving this library. Its fantastic and works amazingly.

    Second: Client wants google analytics. Anyone have any best practices there? Should I just put it in a

    document.addEventListener("turbolinks:load", function() {});
    

    function? Would that work?

    If the answer is that its not really going to work with Turbolinks, I'm willing to accept that. Just wondering if anyone is using it successfully right now.

    opened by gregblass 20
  • Disabling Turbolinks on a particular page

    Disabling Turbolinks on a particular page

    I'm wondering if there's way to disable Turbolinks on a particular page? I know one can disable Turbolinks via the incoming link, but often we don't have control over the incoming link (say in a CMS where an end user has created a link to the page).

    In my particular situation, I'm having issues with the way Safari doesn't save the contents of a cloned textarea. In this case I'd like to prevent Turbolinks from running on this page. When I disable Turbolinks on the incoming link, the page loads like normal, then if I fill out the form, click another link on the page (leading to a turbolinks-enabled page), then click back, Turbolinks has kicked in again and I get the cloned copy of the form with the broken textarea. If I disable caching I get a blank copy of the from rather than what was previously filled in.

    Is it possible for the browser to handle the back function when Turbolinks knows the previous page was turbolinks-disabled?

    opened by brendon 18
  • Restoration visits needed on mobile web after form submit

    Restoration visits needed on mobile web after form submit

    Here's my app flow:

    1. Index page. Stack is: [Index]

    2. User clicks through to a show page. Stack is: [Index][Show]

    3. User clicks through to an edit page. Stack is: [Index][Show][Edit]

    4. User submits a remote form. Validations pass, Turbolinks does its magic with a redirect_to and the user is back to the show page.

    Now here's the issue: the stack is now: [Index][Show][Show]

    The user hits the back button and expects to go back to the Index page, but they have to do it twice.

    Any ideas of how I could essentially make the stack go backwards (this is what a restore is, right?) after a form submit?

    opened by gregblass 18
  • IE 11 issue - Loading specific script tag in head section in Turbolinks

    IE 11 issue - Loading specific script tag in head section in Turbolinks

    Describe the bug Turbolinks is loading the body section of the page alone. I need to run a script in the head section on every page, where the script is working only when it is reloaded. Is there any option to reload the specific script alone in Turbolinks, instead of reloading every page all the time?

    To Reproduce Add a script in the head section, Navigate to the Turbolinks page, the script is not working in IE since it is not loading the script.

    I have tried, data-turbolinks-track="reload" in the particular script, but it is reloading the pages every time. Is it possible to load the script in turbolinks itself, without reloading the pages every time?

    Expected behavior Turbolinks should load the specific script in the head section, without reloading the pages every time.

    Details:

    • Operating System: Windows
    • Browser: IE 11
    • Turbolinks Version: v5.2.0
    bug 
    opened by saranya-sanju 0
  • Bump path-parse from 1.0.6 to 1.0.7

    Bump path-parse from 1.0.6 to 1.0.7

    Bumps path-parse from 1.0.6 to 1.0.7.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Redirect url with anchor not working.

    Redirect url with anchor not working.

    I am using Laravel, and when I redirect after a form, I want to include an anchor which I can do like so:

    return Redirect::to(URL::previous() . '#notes')
        ->withSuccess('Successfully created a note.');
    

    Which is: http://localhost/contact/1#notes

    But turbo doesn't use. the anchor in the URL bar, it just uses the URL: http://localhost/contact/1

    Is there anyway to allow turbo to update the address bar with the anchor of a redirect?

    question 
    opened by natecorkish 0
  • error Uncaught DOMException: Failed to execute 'setAttribute' on 'Element': '{$nonce}' is not a valid attribute name

    error Uncaught DOMException: Failed to execute 'setAttribute' on 'Element': '{$nonce}' is not a valid attribute name

    Describe the bug laravel 8 livewire 2 turbolinks 5.2

    turbolinks.min.js:9 Uncaught DOMException: Failed to execute 'setAttribute' on 'Element': '{$nonce}' is not a valid attribute name.
        at r (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:16771)
        at o.e.createScriptElement (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:16644)
        at o.copyNewHeadScriptElements (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:18617)
        at o.mergeHead (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:17652)
        at o.render (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:17404)
        at Function.e.render (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:16240)
        at t.renderSnapshot (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:22767)
        at t.render (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:22485)
        at r.render (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:10:755)
        at r.<anonymous> (https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js:9:27157)
    

    To Reproduce demo : https://newtest.minifatura.com/en

    Steps to reproduce the behavior:

    1. Go to ' https://newtest.minifatura.com/en'
    2. Click on 'Cart' or Account -> login or register
    3. See error

    Expected behavior in head tag :

      @livewireScripts
    
    
    
       <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/turbolinks.min.js"></script>
       <script src="https://cdn.jsdelivr.net/gh/livewire/[email protected]/dist/livewire-turbolinks.js"
           data-turbolinks-eval="false" data-turbo-eval="false"></script>
      
    

    Details (please complete the following information):

    • Operating System: Windows 10
    • Browser edge
    • Turbolinks Version v5.2.0
    • laravel Version v8
    • livewire Version v2
    bug 
    opened by samehdoush 1
  • Bump lodash from 4.17.15 to 4.17.21

    Bump lodash from 4.17.15 to 4.17.21

    Bumps lodash from 4.17.15 to 4.17.21.

    Commits
    • f299b52 Bump to v4.17.21
    • c4847eb Improve performance of toNumber, trim and trimEnd on large input strings
    • 3469357 Prevent command injection through _.template's variable option
    • ded9bc6 Bump to v4.17.20.
    • 63150ef Documentation fixes.
    • 00f0f62 test.js: Remove trailing comma.
    • 846e434 Temporarily use a custom fork of lodash-cli.
    • 5d046f3 Re-enable Travis tests on 4.17 branch.
    • aa816b3 Remove /npm-package.
    • d7fbc52 Bump to v4.17.19
    • Additional commits viewable in compare view
    Maintainer changes

    This version was pushed to npm by bnjmnt4n, a new releaser for lodash since your current version.


    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v5.3.0-beta.1)
  • v5.3.0-beta.1(Mar 11, 2019)

    • Ported Turbolinks to TypeScript [#445]
    • Fixed an issue with navigation when Turbolinks is loaded by a