Reputation: 1160
A piece of JavaScript I wrote (which lives in app/assets/javascripts/tenant_content.js) wasn't working so I boiled it down to the following in order to test it:
$(document).ready(function() {
console.log("Test");
});
When I refresh the page nothing is logged to the console.
If I remove the console.log
from within the document.ready
then it prints just fine. The strange thing is it also works if I move it to one of my other JavaScript files. It seems to be the combination of being in this particular file and being within the document.ready
function that causes it not to work. Any ideas why?
Note: I'm not using Turbolinks.
Thanks
Upvotes: 1
Views: 1154
Reputation: 1160
There was an error in a different JavaScript file that was stopping the rest of the JavaScript from running. The reason it was specific to one file was because it was the only file that came after the error file in the tree:
javascripts
counter.js
notices.js
stripe.js << this is where the error occurred...
tenant_content.js << ...so the JS in this file wasn't running
I hadn't realised that anything after the error wouldn't run.
Upvotes: 1
Reputation: 10898
Unless you've removed it, you will by default have Turbolinks running.
Instead of doing a full page load when you click links, it'll be doing XHR requests and replacing the body
using javascript.
Because of this, you don't experience any document.ready
events. Instead you should be using one of these, depending on which version you are running:
$(document).ready(myFunc); // What you're currently doing, but isn't working
$(document).on('page:load', myFunc); // Classic Turbolinks (Rails 4)
$(document).on('turbolinks:load', myFunc); // Turbolinks 5 (Rails 5)
Upvotes: 4
Reputation: 1036
This means that document.ready
fired before this event was binded. So your DOM is ready before script is loaded.
If this tag is at the bottom of page, put it up. Or remove asynch
and deferred
attributes.
Upvotes: 0