With Rails 4.2, how to load JavaScript specific to one ControllerMethod Articles#New

206 views Asked by At

Currently, my application.js file includes:

//= require jquery
//= require tether
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require ckeditor/init
//= require_tree .

The problem is ckeditor is being loaded on every page when I only need it on one admin like view Articles#New.

What is the correct way in Rails 4.2, to make ckeditor's JS only load on the Articles#New view?

2

There are 2 answers

2
Vijay Chouhan On

Please follow some steps

  1. Remove from application.js //= require ckeditor/init

  2. at page articles/new.html.erb add following line

javascript_include_tag "ckeditor/init"

  1. in config/initializers/assets.rb add following lines
  Rails.application.config.assets.precompile += %w( ckeditor/* )
0
kevinluo201 On

I think @Vijay's answer is exactly the right one. The config.js not found problem is another problem. The url is probably hard coded in the init.js, because "ckeditor/config.js" seems not like normal precompiled filename which usually looks like config-7efjsdhfduey44xxxxxx.js.

The assets/ dir only has precompiled files in production so the config.js is not found.

You can:

  1. change init.js to init.js.erb
  2. change every path it uses in the file to "asset_path", ex: 'config.js to <%= asset_path 'ckeditor/config.js' %>
  3. do 1,2 for every file under ckeditor/

When using Sprocket in production, the right filename is important. or you can just include the ckeditor from CDN and forget all about this j/k