Optimizing Website Performance with Turbolinks 5: Ensuring JavaScript Loads Efficiently

If you want to see a clear example of the problem I am facing, feel free to check out my sample application. Visit the site, click on a link to another page, then use your browser's back button to return to the previous page and navigate forward again. You'll hopefully understand what I'm trying to explain.

Here is the code for the previous page:

<h1>Form page</h1>
<div id="rating-form">
  <label for="rating-form"> Rating </label>
</div>

I encountered an issue when loading my JavaScript code with this snippet:

$(document).ready(function(){});

The script didn't work as expected until the full page loaded. After reading up on it, I found this helpful solution:

$(document).on('turbolinks:load', function() {

  $('#rating-form').raty({

    path: '/assets/',
    scoreName: 'review[rating]', 
    score: function(){
        return 0
    },


  });

});

This implementation resulted in a bug within the sample application.

I tried using the gem 'jquery-turbolinks' based on this discussion, but unfortunately, it doesn't seem to work well with turbolinks 5.

If anyone has suggestions on how to resolve this issue, please let me know!

Answer №1

Make sure to eliminate it prior to navigating away from the page:

$(document).on('turbolinks:before-cache', function() {
  // Be sure to save the current state (such as score) before
  // executing this action and reload it during turbolinks:load
  $('#rating-form').raty('destroy')
});

Answer №2

Instead of using turbolinks:visit, I would recommend utilizing the load event.

$(window).load(function() {

  $('#rating-form').raty({

    path: '/assets/',
    scoreName: 'review[rating]', 
    score: function(){
        return 0
    },


  });

});

The reason for this recommendation is that turbolinks:visit is triggered with every page visit, including back and forward navigation. On the other hand, the window.onLoad event occurs only after the initial page load, which happens when you first click a link (as it sends an AJAX request). This means that onLoad is called once the AJAX response has been loaded, excluding subsequent back and forward navigation as they do not trigger new requests when using turbolinks.

In most cases, turbolinks:visit will work fine if the function you define remains idempotent across page changes (no adding or removing DOM elements or updating JS history). However, in your case where the .raty(...) function appends elements into #rating-form, the code above will keep appending these elements continuously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React Ref: Invariant Violation when trying to addComponentAsRefTo

I'm encountering an issue while attempting to add a ref to a React component. The error message I'm seeing is as follows: invariant.js:39Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding ...

Attempting to activate cookies, however receiving a message indicating that cookies are not enabled

When trying to log in to a page using request in my node.js server, I set 'jar' to true like this: var request = require('request'); request = request.defaults({jar: true}); After that, I make a post request with the login details: r ...

What is the best method to create random coordinates that fall outside of the circle located within a rectangular area?

Suppose the following scenario: A rectangular area with dimensions length l and breadth b A circle with a radius r The circle is positioned inside the rectangular area as depicted in the image below Check out the image here - Red areas show expected even ...

Using Angular routing with html5mode on an ASP.NET backend allows for

My AngularJS application is based on an ASP.NET project and uses html5mode, which works perfectly fine unless I try to pass route parameter(s). Here is the Angular routing code: $locationProvider.html5Mode(true); $routeProvider.when('/accounts&ap ...

AngularJS - ng-repeat not updating when property array changes

I have a loop in my HTML using ng-repeat: <div class="row"> <div ng-repeat="item in model.painel track by item.codigoIncidente"> <strong>{{item.restante.horaMinutoSegundo}}</strong> </div> </div> In ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

Preventing the Vue compiler from managing static assets: A step-by-step guide

In my Vue 3 application, I have a variety of static assets that are organized in their own file structure separate from the app's source directory. Fortunately, my web server is configured to serve files from both the Vue build directory and the stati ...

When using JSON.stringify, the property value can be displayed but direct access to the property itself

Encountering an issue while trying to access a property of a JSON object directly from a MongoDB document, leading to an undefined value. Surprisingly, the use of JSON.stringify() generates a value for that specific property. Is there a way to access the p ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

What is the best way to locate a div element with a specific style?

What is the method to locate a div element by its style? Upon inspecting the source code in IE6, here is what I find: ...an><div id="lga" style="height:231px;margin-top:-22px"><img alt="Google"... How can this be achieved using JavaScript? ...

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

How to use jQuery to delete the final table in an entire HTML document

This situation is really frustrating: When I make a jQuery Ajax call, the success callback returns an entire HTML page. The returned page looks like this: <html> <head> <title>Title</title> <body> <table></table> ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

An icon wrapped in an <a> element using the link_to tag

I am encountering an issue with a navbar button: <%= link_to new_post_path do %> <a class="btn-navbar"><i class="fa fa-plus" aria-hidden="true"></i></a> <% end %> The button is unresponsive and does not direct me to ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

What is the best way to retrieve multiple variables using Express.js on Node.js?

Trying to fetch Form data from an HTML page to a Node Js server. The HTML file is named index.html <body> <nav> <ul> <li> <a href="#" class="button add">Add Product</a> <div class="dialog" style="displ ...

Is there an easy method for sorting through JSON data with various criteria?

After receiving a response from my web service containing an array of objects, I am looking to filter the data based on various combinations of values. What is the most efficient way to do this without impacting the performance of my web service? Data: Th ...

Show the result of file upload, whether it was successful or not, using ReactJS

I need to implement an Ajax call for uploading a file to the server. I want to display success and failure messages based on the outcome of the file upload process. $.ajax({ url: "https:my_url", data: {my data: my_data}, method : "POST", success: ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...