Think when Rails (turbolinks) doesn't load the page for the first time

First post

This is the first post, so please be kind to me.

environment

Ruby 2.6.5 Rails 6.0.3.2

Overview

When creating an application with Rails, the behavior sometimes did not go well when the page was changed.

I myself am quite clogged up, so I will leave it as a memorandum. Also, I would like to be able to give as much as possible to people who are similarly clogged.

Goal you want to achieve

Provide information that will give you a hint to those who are having trouble loading the page for the first time. Consider loading a page when using turbolinks.

The problem you want to solve

The first load of a page does not work when using Rails turbolinks.

What is turbolinks

・ What is turbolinks? Gem introduced by default from Rails 4.0 ・ Turbolinks is a library that speeds up screen transitions (not updating the entire screen, but updating only a part of the screen) -JavaScript may not work properly due to turbolinks

Flow of page transition using turbolinks

① The HTML of the page is loaded (2) Load the CSS and JavaScript referenced in the page ③ Render the page (display the page based on the information)

If multiple CSS and JS files exist in step (2), multiple communications will be performed between the browser and the Web server, and the communication speed will slow down.

That's where the "asset pipeline" framework came in (since Rails 3.0). The asset pipeline is a mechanism that "concatenates and compresses JavaScript, CSS, and image files that you want to use in a Ruby on Rails application into one file while making development work easier."

This asset pipeline has reduced communication between the browser and the server.

And new additions to the asset pipeline from Rails 4.0 are "turboliks".

"Turbolinks" extracts only the "title" and "body" of the current page and converts them to the new HTML "title" and "body" when the page transitions. This eliminates the need for the browser to reacquire CSS and JavaScript, which speeds up the process.

Notes on turbolinks

If you use turbolinks, JavaScript that starts from page load will not work.

Normally, the load event occurs when the page is loaded. However, the load event does not occur when the screen is switched by turbolinks.

solution

Therefore, in the following description, make it work by first loading, reloading, and page switching (first choice).

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

Let's look at an example.

$(document).on('turbolinks:load', ()=> {
  $('#image-box').on('change', '.js-file', function(e) {
    //Determine if this has a compilation class with the hasClass method
    const conpilation = $(this).hasClass('conpilation');
    if (!conpilation) {
      //Make an input using the first number of fileIndex(.append appends a tag at the end of the element)
      $('#image-box').append(buildFileField(fileIndex[0]));
      //Here`item_images_attributes_${fileIndex[0]}_image`)And const html id="item_images_attributes_${index}_image">Is OK if they are together
      $('.ListingMain__entire__menu__list__field__display__content').attr('for', `item_images_attributes_${fileIndex[0]}_image`)
      // shift()The method removes the first element from the array and returns that element. This method changes the length of the array.
      fileIndex.shift();
      //Add 1 to the last number(.push is a method for adding a new element to the end of an array)
      fileIndex.push(fileIndex[fileIndex.length - 1] + 1);
    } else {
      return false;
    }
  });
});

This should work! !! !! I was surprised, but the behavior becomes strange only when loading for the first time.

Second choice

Try to fire when the screen loads.


$(document).on('ready page:load', ()=> {

But even this doesn't work. ..

Third choice

If this doesn't work, there's nothing you can do about it.

= link_to new_item_path, class: "Sell__listing", data: {"turbolinks" => false} do

In conclusion, the above description now works fine the first time the page loads.

data: {"turbolinks" => false}

This description is the point. With this, turbolinks can be turned off only for the transition destination page.

Supplement

From Rails 6.0 and later versions, a gem called Webpacker is introduced as standard. Webpack is a framework for managing various JavaScripts required when creating a web application. Modern web application development uses various JavaSctipt libraries, which manage their dependencies (module bundler).

Webpacker In Rails so far, the asset pipeline was used to manage JavaScript etc. However, as the JavaScript library has been enhanced, the policy of using Webpack is being changed from Rails 6.0 or later.

This time, I used jQuery, so there was no problem implementing it in the asset pipeline. In the future, you may use Webpacker. However, it seems that Webpack can be installed in Rails applications without using Webpacker. There is still a lack of study in this area, so I am thinking of continuing my studies.

Summary

If you are using Rails 4.0 or later and the page does not load well, you may be able to implement it well by considering the above.

reference: https://qiita.com/hiroyayamamo/items/b258acbaa089d9482c8a https://www.ryotaku.com/entry/2019/01/15/213420

At the end

We hope you find this article useful. From now on, I would like to share what I have learned so that I can give as much as possible. Thank you.

Recommended Posts

Think when Rails (turbolinks) doesn't load the page for the first time
Learning memo when learning Java for the first time (personal learning memo)
[Rails] I tried using the button_to method for the first time
Spring Boot for the first time
Spring AOP for the first time
Introduction to java for the first time # 2
Learning for the first time java [Introduction]
[Ruby on Rails] When logging in for the first time ・ How to split the screen in half using jQuery
I tried using Docker for the first time
Walls hit by Rspec for the first time
Android Studio development for the first time (for beginners)
I tried touching Docker for the first time
Learn for the first time java # 3 expressions and operators
Oreore certificate https (2020/12/19) for the first time with nginx
When the vagrant command doesn't work for some reason
[Android studio / Java] What you don't understand when you touch it for the first time
How to study kotlin for the first time ~ Part 2 ~
How to study kotlin for the first time ~ Part 1 ~
A summary of what Java programmers find when reading Kotlin source for the first time
Measures for taking a long time to load images (Rails)
Modeling a Digimon with DDD for the first time Part 1
What to do if the Rails page doesn't appear in Rails tutorial 1.3.2
[Rails] How to change the page title of the browser for each page
[Beginner] When rails s doesn't work
[First Java] Make something that works with Intellij for the time being
The story of releasing the Android app to the Play Store for the first time.
Ruby on Rails DB Tips for creating methods to reduce the load
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
Creating an app and deploying it for the first time on heroku
Programming for the first time in my life Java 1st Hello World
Ideal and reality that I felt when I used Optional for the first time ~ Implementation of cache using Map ~