Help us understand the problem. What is going on with this article?

railsでjQuery/JavaScriptがうまく動かない時の対処法

More than 1 year has passed since last update.

html内でapplication.jsが呼ばれるように設定しているのに、なかなか動かずハマったので解決策をご紹介します。結論だけ書くと、”assets/javascriptより先にjQueryのソースを読む”です。

jQueryを読み込ませる→スクリプトを読み込む

問題のHTMLがこちら

application.html.erb
<head>
    <title>SiteTitle</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application' %>

  </head>

Stack Overflowには、"turbolinksが悪さをしている"、"jQueryを読み込む"という解決策が乗っていましたので、試して見ましたが、なかなかうまくいかず。

application.html.erb
<head>
    <title>SiteTitle</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application' %>

<!-- /この部分を追加しました -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- /ここまで -->
  </head>

しかし、このやり方だとスクリプト読み込み→jQuery読み込みという順番になります。この順番を逆にするだけでうまくいきました。

application.html.erb
<head>
    <title>SiteTitle</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>

<!-- /jQueryを読み込む -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- /スクリプトを読み込む -->
    <%= javascript_include_tag 'application' %>



  </head>

試して見てくださいね。

keiy121
フレームワーク:Flutter / Vue.js / Ruby on Rails 言語: Ruby / Javascript / Dart インフラ:Linux (CentOS系が得意)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした