rails/jquery-rails

jQuery not loading

johnpitchko opened this issue · 3 comments

Followed the instructions provided.

Added gem 'jquery-rails' to my Gemfile. Did bundle update and confirmed that I saw Using jquery-rails 4.4.0` in the output.

Added the following to app/assets/javascripts/application.js:

//= require jquery
//= require rails-ujs

To test that jQuery works, I added the following to one of my index.erb files:

<script>
  window.onload = function() {
    if (window.jQuery) {
        // jQuery is loaded
        alert("Yeah!");
    } else {
        // jQuery is not loaded
        alert("Doesn't Work");
    }
}
</script>

When I restart rails and refresh the page, I receive the Doesn't work alert.

However, if I add the usual jQuery script tag to the page:

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

I receive the Yeah! alert.

Am I missing something here? TIA

I also can't get jquery to load. Can't find any explanation on the internet about why.

Same issue here.

joaku commented

If you are using webpacker (gem 'webpacker'), then to have to map the $ an jquery instructions to the compiling:

#config/webpack/enviroment.js


var webpack = require('webpack');

const { environment } = require('@rails/webpacker')

environment.plugins.prepend('Provide',
	new webpack.ProvidePlugin({
		$: 'jquery',
		jQuery: 'jquery',
		Popper: ['popper.js', 'default']
	}));

module.exports = environment