简体   繁体   中英

Why does JS only load whenever the page is first time loaded or refreshed?

I have had this problem for a while whenever i builds Rails apps. Basically what happens is that every time you load the app and you have some sort of javascript code wether it's a tooltip or a datepicker it will only load it the first time you open the page or until you refresh the page

So lets say you decide to visit the Services pages and you want to choose a date with the following code

$(document).ready ->
   $("[data-behaviour~=datepicker]").datepicker(
   todayBtn: "linked", 
   todayHighlight: true, 
   startDate: "(Time.current, :format => :datepicker)"
   format: "yyyy/mm/dd"
)

This code will load fine on first page load or until the page is refreshed, however if you go back and forth between pages the code for some reason won't load. As in the datepicker won't appear again until you refresh the page.

This happens in both dev and production. Anyone know whats up and care to explain please? Am i doing something wrong?

And no, the code doesn't go in application.js but rather in a seperate .js file and then gets called from application.js via the require tree i presume.

This is due to Turbolinks ajax'ifying your links so the ready event only gets triggered on first page load.

TL;DR

You can use $(document).on "page:change", -> instead of $(document).ready ->

How Turbolinks works

Turbolinks attaches a click handler to all on the page. If your browser supports PushState, Turbolinks will make an Ajax request for the page, parse the response, and replace the entire of the page with the of the response. It will then use PushState to change the URL to the correct one, preserving refresh semantics and giving you pretty URLs

Reference: http://guides.rubyonrails.org/working_with_javascript_in_rails.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM