Rails 7.1生产环境JavaScript加载失败问题求助
Rails 7.1生产环境JS加载失败(CDN配置相关)
本地运行正常,部署到生产环境后JavaScript无法加载,唯一差异是启用了CDN。相关配置和代码如下:
相关文件代码
app/views/application.html.erb
<!DOCTYPE html> <html> <head> <title><%= Rails.application.config.metadata["name"] %></title> <meta name="description" content="<%= Rails.application.config.metadata["description"] %>"> <meta name="viewport" content="width=device-width,initial-scale=1"> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= favicon_link_tag "favicon.ico" %> <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %> <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> </head> <body class="min-w-full bg-white flex flex-col"> <%= render "layouts/navigation" %> <main class="flex-grow"> <%= yield %> </main> <%= render "layouts/modal" %> </body> </html>
app/javascript/application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails import "@hotwired/turbo-rails" import "controllers" // Navbar menu document.addEventListener("turbo:load", () => { var menu_button = document.getElementById("mobile-menu-button"); var menu = document.getElementById("mobile-menu"); if (menu_button) { menu_button.addEventListener("click", () => { menu.classList.toggle("hidden"); }); } });
config/environments/production.rb
... config.asset_host = ENV.fetch("RAILS_ASSET_HOST") { nil } ...
出现的警告信息
[警告] 资源 https://cdn.multiplecurrenciesforynab.com/assets/turbo.min-dfd93b3092d1d0ff56557294538d069bdbb28977d3987cb39bc0dd892f32fc57.js 已通过link preload预加载,但在窗口加载事件后的几秒内未被使用。请确认它不是无意义的预加载。
解决方法
1. 配置CSP允许CDN资源
浏览器的内容安全策略(CSP)会阻止未授权域名的资源加载,需要把CDN域名加入到script-src和style-src指令中。编辑config/initializers/content_security_policy.rb:
Rails.application.config.content_security_policy do |policy| if Rails.env.production? policy.script_src :self, :https, "cdn.multiplecurrenciesforynab.com" policy.style_src :self, :https, "cdn.multiplecurrenciesforynab.com" # 若字体、图片等资源也用CDN,需对应添加到font_src、img_src policy.font_src :self, :https, "cdn.multiplecurrenciesforynab.com" policy.img_src :self, :https, "cdn.multiplecurrenciesforynab.com", :data else policy.default_src :self, :https policy.script_src :self, :https, :unsafe_inline, :unsafe_eval policy.style_src :self, :https, :unsafe_inline end end
2. 校验Importmap资源映射
检查config/importmap.rb中资源映射是否正确,确保预加载路径和CDN上的文件匹配。比如Turbo的配置:
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
如果使用本地编译的资源,要确认编译后的文件已正确上传到CDN,且文件名哈希和页面引用一致。
3. 处理预加载未使用的警告
这个警告说明预加载的Turbo文件未被正确执行,可尝试:
- 确认
javascript_importmap_tags生成的预加载链接路径和CDN实际文件路径一致 - 若不需要预加载,可在
importmap.rb中移除preload: true:
pin "@hotwired/turbo-rails", to: "turbo.min.js"
4. 验证CDN资源可访问性
直接访问警告中的CDN资源URL,确认文件能正常下载。若返回404,检查CDN文件上传是否完整或路径配置是否错误。
5. 清除生产环境缓存
部署后执行以下命令,确保最新的资产路径生效:
rails assets:precompile RAILS_ENV=production rails cache:clear RAILS_ENV=production
内容的提问来源于stack exchange,提问作者Ricardo
相关产品推荐
相关产品推荐

