getscript Loading Over an Over Again

Turbolinks is no longer under agile development

Please note that Turbolinks is no longer under active evolution. Information technology has been superseded by a new framework called Turbo, which is role of the Hotwire umbrella.

Turbolinks

Turbolinks® makes navigating your web application faster. Become the performance benefits of a single-page application without the added complication of a client-side JavaScript framework. Employ HTML to render your views on the server side and link to pages every bit usual. When y'all follow a link, Turbolinks automatically fetches the folio, 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. Reply with full HTML pages, non fractional page fragments or JSON.
  • Respects the web. The Back and Reload buttons work only equally you'd wait. Search engine-friendly past pattern.
  • Supports mobile apps. Adapters for iOS and Android allow you build hybrid applications using native navigation controls.

Supported Browsers

Turbolinks works in all modern desktop and mobile browsers. Information technology 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 parcel. If you load Turbolinks every bit a CommonJS or AMD module, first require the module, then call the provided start() role.

Installation Using Ruby on Rails

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

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

The gem as well provides server-side support for Turbolinks redirection, which tin be used without the asset pipeline.

Installation Using npm

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

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

  2. Crave and start Turbolinks in your JavaScript package:

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

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

Table of Contents

Navigating with Turbolinks

  • Each Navigation is a Visit
  • Application Visits
  • Restoration Visits
  • Canceling Visits Before They Start
  • Disabling Turbolinks on Specific Links

Building Your Turbolinks Application

  • Working with Script Elements
    • Loading Your Awarding's JavaScript Bundle
  • Understanding Caching
    • Preparing the Page to be Cached
    • Detecting When a Preview is Visible
    • Opting Out of Caching
  • Installing JavaScript Behavior
    • Observing Navigation Events
    • Attaching Behavior With Stimulus
  • Making Transformations Idempotent
  • Persisting Elements Across Folio Loads

Advanced Usage

  • Displaying Progress
  • Reloading When Assets Change
  • Ensuring Specific Pages Trigger a Total Reload
  • Setting a Root Location
  • Following Redirects
  • Redirecting After a Form Submission
  • Setting Custom HTTP Headers

API Reference

  • Turbolinks.visit
  • Turbolinks.clearCache
  • Turbolinks.setProgressBarDelay
  • Turbolinks.supported
  • Total List of Events

Contributing to Turbolinks

  • Building From Source
  • Running Tests

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 so renders the HTML response.

During rendering, Turbolinks replaces the electric current <body> chemical element outright and merges the contents of the <head> chemical element. The JavaScript window and certificate objects, and the HTML <html> element, persist from ane rendering to the adjacent.

Each Navigation is a Visit

Turbolinks models navigation equally 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 re-create of the page from cache, rendering the concluding response, and updating the scroll position.

There are two types of visit: an application visit, which has an action of advance or supplant, and a restoration visit, which has an action of restore.

Application Visits

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

An awarding visit e'er 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 folio from cache immediately after the visit starts. This improves the perceived speed of frequent navigation betwixt the same pages.

If the visit's location includes an ballast, Turbolinks will attempt to scroll to the anchored element. Otherwise, it volition scroll to the elevation of the page.

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

Advance visit action

The default visit action is accelerate. During an advance visit, Turbolinks pushes a new entry onto the browser'southward 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 supercede 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 activeness: "replace" option to Turbolinks.visit:

              Turbolinks              .              visit              (              "/edit"              ,              {              activeness:              "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 blitheness.

Restoration Visits

Turbolinks automatically initiates a restoration visit when you navigate with the browser's Back or Frontward 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 folio from cache without making a request. Otherwise, it volition retrieve a fresh copy of the page over the network. Encounter Agreement Caching for more than details.

Turbolinks saves the ringlet 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 endeavor to comment links or invoke Turbolinks.visit with an activity of restore.

Canceling Visits Before They Get-go

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

Listen for the turbolinks:earlier-visit effect to exist notified when a visit is near to start, and use outcome.data.url (or $upshot.originalEvent.data.url, when using jQuery) to check the visit's location. Then abolish 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 exist 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, employ information-turbolinks="true":

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

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

Edifice Your Turbolinks Application

Turbolinks is fast because it doesn't reload the page when yous follow a link. Instead, your application becomes a persistent, long-running procedure in the browser. This requires you to rethink the style you structure your JavaScript.

In particular, yous can no longer depend on a full page load to reset your surroundings every time you navigate. The JavaScript window and document objects retain their state across folio changes, and any other objects you go out in retentiveness volition stay in memory.

With awareness and a little extra care, you lot 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 nowadays on the initial page load.

When you navigate to a new page, Turbolinks looks for any <script> elements in the new page'due south <caput> which aren't nowadays on the current page. And so information technology appends them to the current <head> where they're loaded and evaluated by the browser. You lot tin utilise this to load boosted JavaScript files on-need.

Turbolinks evaluates <script> elements in a page'southward <torso> each time it renders the folio. You can apply inline trunk scripts to gear up upwardly per-folio JavaScript country or bootstrap customer-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 information-turbolinks-eval="imitation" if you do non desire Turbolinks to evaluate them later rendering. Note that this notation volition not prevent your browser from evaluating scripts on the initial page load.

Loading Your Awarding's JavaScript Parcel

Always make sure to load your application's JavaScript packet 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 functioning reasons, consider using the <script defer> attribute instead. It has widespread browser back up and allows you to keep your scripts in <head> for Turbolinks compatibility.

Y'all should also consider configuring your asset packaging arrangement to fingerprint each script and then it has a new URL when its contents modify. Then you can utilize the data-turbolinks-track attribute to strength a full page reload when you deploy a new JavaScript package. See Reloading When Assets Change for information.

Understanding Caching

Turbolinks maintains a cache of recently visited pages. This cache serves two purposes: to brandish pages without accessing the network during restoration visits, and to improve perceived performance by showing temporary previews during awarding visits.

When navigating by history (via Restoration Visits), Turbolinks volition 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 information technology as a preview while simultaneously loading a fresh copy from the network. This gives the illusion of instantaneous folio loads for frequently accessed locations.

Turbolinks saves a copy of the current page to its cache just before rendering a new page. Annotation 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:earlier-cache effect if you demand to set up the certificate before Turbolinks caches it. You can utilize this event to reset forms, plummet expanded UI elements, or tear downward whatever 3rd-party widgets so the page is ready to be displayed over again.

              certificate              .              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 enshroud. You can check for the presence of this aspect 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 tin can control caching behavior on a per-page basis by including a <meta name="turbolinks-enshroud-control"> element in your page's <head> and declaring a caching directive.

Apply 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 folio should non exist cached at all, use the no-cache directive. Pages marked no-enshroud will always be fetched over the network, including during restoration visits.

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

To completely disable caching in your awarding, 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 gear up 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 beliefs 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 later on every Turbolinks visit.

You tin can detect the turbolinks:load consequence in place of DOMContentLoaded to set up up JavaScript beliefs after every page modify:

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

Proceed in mind that your application will not always be in a pristine state when this outcome is fired, and yous may need to clean upwardly behavior installed for the previous page.

Also note that Turbolinks navigation may not be the only source of folio updates in your awarding, then you may wish to move your initialization lawmaking into a separate role which yous can phone call from turbolinks:load and anywhere else you may alter the DOM.

When possible, avoid using the turbolinks:load result to add other effect listeners directly to elements on the folio torso. Instead, consider using event delegation to register upshot listeners once on document or window.

See the Full List of Events for more information.

Attaching Beliefs With Stimulus

New DOM elements can appear on the page at any time by mode of Ajax asking handlers, WebSocket handlers, or customer-side rendering operations, and these elements often need to exist initialized as if they came from a fresh page load.

Yous can handle all of these updates, including updates from Turbolinks folio loads, in a unmarried place with the conventions and lifecycle callbacks provided by Turbolinks' sister framework, Stimulus.

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

              <              div              information-controller="hello">              <              input              data-target="hi.name"              type="text">              <              button              information-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              (              )              {              panel              .              log              (              `How-do-you-do,                                  ${                  this                  .                  name                  }                !`              )              }              get              proper 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. Equally a issue, it handles Turbolinks page changes the same fashion information technology handles whatever other type of DOM update.

See the Stimulus repository on GitHub for more than information.

Making Transformations Idempotent

Often yous'll want to perform customer-side transformations to HTML received from the server. For example, you lot might want to employ the browser's knowledge of the user's current time zone to grouping a collection of elements by appointment.

Suppose you have annotated a gear up of elements with data-timestamp attributes indicating the elements' creation times in UTC. Y'all have a JavaScript role that queries the document for all such elements, converts the timestamps to local fourth dimension, and inserts date headers before each chemical element that occurs on a new day.

Consider what happens if y'all've configured this function to run on turbolinks:load. When yous 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 push—Turbolinks restores the page, fires turbolinks:load again, and your office inserts a 2d set of date headers.

To avoid this problem, make your transformation function idempotent. An idempotent transformation is safe to apply multiple times without irresolute the outcome beyond its initial application.

One technique for making a transformation idempotent is to keep track of whether you lot've already performed it by setting a data attribute on each processed chemical element. When Turbolinks restores your page from enshroud, these attributes will still be present. Detect these attributes in your transformation function to decide which elements take already been processed.

A more robust technique is simply to notice the transformation itself. In the date grouping example above, that means checking for the presence of a appointment divider before inserting a new ane. This approach gracefully handles newly inserted elements that weren't processed by the original transformation.

Persisting Elements Across Folio Loads

Turbolinks allows you to mark certain elements as permanent. Permanent elements persist across page loads, so that any changes y'all make to those elements exercise not need to be reapplied later on navigation.

Consider a Turbolinks application with a shopping cart. At the acme of each page is an icon with the number of items currently in the cart. This counter is updated dynamically with JavaScript every bit items are added and removed.

Now imagine a user who has navigated to several pages in this application. She adds an detail to her cart, and then presses the Dorsum push in her browser. Upon navigation, Turbolinks restores the previous folio's state from cache, and the cart item count erroneously changes from 1 to 0.

You can avoid this problem by mark the counter element every bit permanent. Designate permanent elements by giving them an HTML id and annotating them with data-turbolinks-permanent.

              <              div              id="cart-counter"              information-turbolinks-permanent              >one item</              div              >            

Earlier each render, Turbolinks matches all permanent elements by id and transfers them from the original folio 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 lot tin 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 past rules that come subsequently.

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

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

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

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

Reloading When Avails Change

Turbolinks can track the URLs of asset elements in <caput> from one page to the side by side and automatically event a full reload if they alter. This ensures that users always have the latest versions of your awarding'south scripts and styles.

Annotate asset elements with data-turbolinks-track="reload" and include a version identifier in your asset URLs. The identifier could exist a number, a last-modified timestamp, or ameliorate, a digest of the nugget's contents, as in the following example.

              <              caput              >              ...              <              link              rel="stylesheet"              href="/application-258e88d.css"              data-turbolinks-track="reload">              <              script              src="/awarding-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-command"> element in the page's <head>.

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

This setting may exist useful equally a workaround for tertiary-party JavaScript libraries that don't interact well with Turbolinks page changes.

Setting a Root Location

By default, Turbolinks just loads URLs with the same origin—i.e. the same protocol, domain name, and port—as the current document. A visit to whatever other URL falls back to a total page load.

In some cases, you may want to further telescopic Turbolinks to a path on the aforementioned origin. For example, if your Turbolinks application lives at /app, and the non-Turbolinks help site lives at /assistance, 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 aforementioned-origin URLs that are prefixed with this path.

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

Following Redirects

When you lot visit location /ane and the server redirects y'all to location /two, you look the browser'south address bar to display the redirected URL.

Still, Turbolinks makes requests using XMLHttpRequest, which transparently follows redirects. In that location's no way for Turbolinks to tell whether a request resulted in a redirect without boosted cooperation from the server.

To work around this problem, ship the Turbolinks-Location header in the terminal response to a visit that was redirected, and Turbolinks will supersede 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 Subsequently 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 folio load. Using Turbolinks you can improve the functioning of class submission without complicating your server-side lawmaking.

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 past 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 Runway engine performs this optimization automatically for non-Get XHR requests that redirect with the redirect_to helper.

Setting Custom HTTP Headers

You can detect the turbolinks:asking-start event to gear up custom headers on Turbolinks requests. Access the request's XMLHttpRequest object via consequence.information.xhr, and so telephone call the setRequestHeader method as many times as yous wish.

For instance, y'all might want to include a asking ID with every Turbolinks link click and programmatic visit.

              document              .              addEventListener              (              "turbolinks:request-outset"              ,              role              (              event              )              {              var              xhr              =              upshot              .              data              .              xhr              xhr              .              setRequestHeader              (              "Ten-Asking-Id"              ,              "123..."              )              }              )            

API Reference

Turbolinks.visit

Usage:

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

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

If location is a cross-origin URL, or falls outside of the specified root (run into 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 outcome on document. Your application can listen for this event and cancel the visit with event.preventDefault() (see Canceling Visits Before They Offset).

Turbolinks.clearCache

Usage:

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

Turbolinks.setProgressBarDelay

Usage:

              Turbolinks              .              setProgressBarDelay              (              delayInMilliseconds              )            

Sets the filibuster after which the progress bar volition appear during navigation, in milliseconds. The progress bar appears afterward 500ms by default.

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

Total List of Events

Turbolinks emits events that let you to track the navigation lifecycle and respond to page loading. Except where noted, Turbolinks fires events on the certificate object.
Notation that when using jQuery, the information on the event must be accessed equally $result.originalEvent.data.

  • turbolinks:click fires when you lot click a Turbolinks-enabled link. The clicked chemical element is the upshot target. Admission the requested location with issue.data.url. Cancel this event to permit the click fall through to the browser as normal navigation.

  • turbolinks:earlier-visit fires before visiting a location, except when navigating by history. Admission the requested location with event.data.url. Cancel this event to prevent navigation.

  • turbolinks:visit fires immediately after a visit starts.

  • turbolinks:request-outset fires earlier Turbolinks issues a network request to fetch the folio. Admission the XMLHttpRequest object with event.data.xhr.

  • turbolinks:asking-end fires afterwards the network request completes. Access the XMLHttpRequest object with result.data.xhr.

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

  • turbolinks:before-return fires before rendering the folio. Access the new <torso> chemical element with event.data.newBody.

  • turbolinks:render fires subsequently Turbolinks renders the page. This outcome fires twice during an awarding visit to a buried location: once after rendering the cached version, and once more after rendering the fresh version.

  • turbolinks:load fires once later on the initial folio load, and again later every Turbolinks visit. Access visit timing metrics with the effect.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 projection is released with a Contributor Code of Conduct. By participating in this project you concur to abide by its terms.

Building From Source

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

              $ yarn install $ yarn build                          

Include the resulting dist/turbolinks.js file in your application'southward 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:

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


© 2022 Basecamp, LLC.

paynemagench83.blogspot.com

Source: https://github.com/turbolinks/turbolinks

0 Response to "getscript Loading Over an Over Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel