简体   繁体   中英

Jquery will not fire document.ready in rails

I cannot get jquery to work for the life of me. I have two pages I'm working on, both require javascript.

The first page is my home page. It has simple coffeescript to display an alert on document load

$(document).ready ->
 alert('ready')

The second page has it's own coffeescript im not going to paste here.

When I load the home page this document.ready does not fire. However, if I load the second page, it's code AND this alert are fired.

What this leads me to believe is that jquery isn't being loaded. So I went ahead and tested a few things

  1. Jquery is the first javascript file included, the home page's javascript file is the second to last one included (last one is application.js).
  2. The second page's script file is included before the home page's script file
  3. Removing turbolinks does not fix it.

So I decided to see if I could get anything to work.

alert 'test'
$(document).ready ->
 alert('ready')

will fire the 'test' alert on the homepage.

Further, if I include script tags at the bottom of the home page and I put in some jquery to prevent form submission it works fine. Below is the code:

<script type="application/javascript">
  $("#formtest").submit(function(e){
  e.preventDefault();
  alert('No submit');
 });
</script>

However,

<script type="application/javascript">
  $(document).ready(function(){
    alert('hello');
  });
</script>

Still doesn't work. Which tells me that the DOM loaded event is not firing for the home page.

EDIT:

It appears the $(document).ready -> ... in the second page's javascript is screwing up this one. Why is that?

As I mentioned in my comment, a solution that worked for me was to have the jquery event fire this way as well:

$(document).on('page:load', yourFunctionHere)

An additional solution is also to install the following gem:

gem 'jquery-turbolinks'

Using that gem will allow you to use the DOM load event to trigger all necessary jquery functions.

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