LoginSignup
15
12

More than 5 years have passed since last update.

【turbolinks】WebページのJavaScriptがリロードしないと動いてくれない問題

Posted at

開発環境できちんと動いていたMaterializeのJS関連

僕が今回多用しまくったのではこいつです。
画面遷移しなくとも、動的処理を行ってくれる。JQueryに依存しています。

  • リロードすると正常
  • リロード前はJQueryが適用できていないように思える

結局何が悪かったのか

  • turbolinks

turbolinksとは

こちらによると

turbolinksはbodyなどhtmlの一部の取っ替えを行い、CSSやJavaScriptを省略するgem。
何がいいかと問われると、高速化ができる。

私はRails4だったので、デフォルトで導入されていました。

これのせいでjQueryのReadyイベントが実行されないとのこと。
基本的にMaterializeはjQuery依存でコードも以下の通り、readyイベントの中にcollapsibleイベントが発火する形。

collapsible.js
document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.collapsible');
    var instances = M.Collapsible.init(elems, options);
  });

  // Or with jQuery

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

READMEによると、以下のように別イベントにするといいらしい。

turbolinks.js
// BAD: this will not work.
$(document).on('ready', function () { /* ... */ });

// OK: these two are guaranteed to work.
$(document).ready(function () { /* ... */ });
$(function () { /* ... */ });

やったこと

今回は高速化の必要もないので、turbolinksを消しました。
Gemfileのturbolinskのgemを消し、bundle update。
app/assets/javascript/application.jsのturbolinks関連を削除。

app/assets/javascript/application.js
//= require jquery
- //= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
- //= require turbolinks

きちんと動作しました。

参考記事

http://o.inchiki.jp/obbr/97
http://kray.jp/blog/must-know-about-turbolinks/

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12