简体   繁体   中英

Rails4 and CoffeeScript: jQuery bindings not working when server returns 304 status code

I am building a new site on Rails 4. I have noticed than when browsing from page to page, Rails (Puma) returns 304, not modified. So far so good. The problem is that when that happens, none of the jQuery bindings on that loaded page seem to be hooked. Thus, none of the page events work (button clicks, etc). There is no ajax involved, just a normal page load.

If I reload the page in the browser, the server then returns 200OK and all bindings are loaded properly. If I paste the JS code on the console, all bindings get hooked properly. It is just the initial page load when the server returns 304, that the bindings do not get set.

My intuition tells me it is jQuery not firing the 'page load' event, and thus not running any of the Javascript on the page. But I am not sure.

Thanks to mu is too short's hint (see comments to the question), I found the answer here: Holder.js doesn't work with turbolinks

Basically, what it means is that instead of using the following code to initialize the scripts on the page...

$ ->
    # CoffeeScript code here

... it is recommended to use the following:

$(document).bind 'page:change', ->
    # CoffeeScript code here

Binding the page:change event instead of the default 'page onload' event ensures your code is run when the server returns 304 for the HTML request.

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