[Java] [Rails] How to load JavaScript in a specific view

less than 1 minute read

Development environment

・Ruby: 2.5.7 Rails: 5.2.4 ・Vagrant: 2.2.7 ・VirtualBox: 6.1 ・OS: macOS Catalina

Premise

Implemented below.

Slim introduction

Implementation

1. Edit application.js

Delete the =. By doing this, the javascript files in assets/javascripts will not be loaded automatically.

application.js


//Change before
//= require_tree

//Change before
// require_tree

2. Edit the environments

If you want to reflect it in the development environment, development.rb, If you want to reflect it in the production environment, edit production.rb.

development.rb


Rails.application.configure do
  # Set the javascript file you want to read individually
  config.assets.precompile += ['gmap.js']
  Note that the # coffee script will give an error if you add an extension!
  config.assets.precompile += ['jquery.jpostal']
end

3. Edit the view

/ Set the javascript file you want to read on this page
= javascript_include_tag'gmap.js'