我正在尝试将js文件加载到应用程序的单个页面中。但这全称为,最终在我的屏幕上产生错误。
我的application.js是:
//= require jquery
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
我的application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Netshow</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<div class='cover-container d-flex w-100 h-100 p-3 mx-auto flex-column'>
<header class='masthead mb-auto'>
<%= render 'shared/navbar' %>
</header>
<%= yield %>
<footer class='mastfoot mt-auto'>
<%= render 'shared/footer' %>
</footer>
</div>
</body>
</html>
我的js文件是:
$(document).on("turbolinks:load", function() {
console.log('teste')
var player = videojs('my_video_1');
var options = {};
player.on('play', function() {
$.ajax({
type: 'POST',
url:"/video_clicks/",
dataType: 'json',
data: {
video_click: { video_id: window.location.pathname.split('/')[2] }
},
success: function(){
$('span.video-count')[0].innerText = parseInt($('span.video-count')[0].innerText) + 1
}
});
});
function showCount(){
var id = window.location.pathname.split('/')[2]
$.ajax({
type: 'GET',
url:"/video_clicks/"+id,
dataType: 'json',
success: function(data){
console.log($('span.video-count')[0])
$('span.video-count')[0].innerText = data
}
});
}
showCount()
});
我只想在应用程序的一页上加载js文件,而根本不加载。我怎样才能做到这一点?我已经尝试过删除application.html.erb中的require_tree添加内容并在我的html文件中设置内容,但是Rails说我必须将文件添加到asset.erb中进行预编译,而当我这样做时,其他页面会重新加载我的js文件。
答案 0 :(得分:1)
在这种情况下,您有多种选择:
params[:controller]
和params[:action]
,如果与特定的页面控制器+操作匹配,则仅加载JS。 (更好的解决方案)赞:
<% if params[:controller] == 'your_controller_name' && params[:action] == 'your_action_name' %>
<%= render partial: 'shared/custom_js' %>
<% end %>
基于上面的代码,我将在我的视图>共享文件夹中创建一个名为custom_js.html.erb
的新文件。然后将脚本写入该文件中<script></script>
标签内。另外,您需要从application.js
文件中删除该脚本文件。
答案 1 :(得分:0)
您只需在页面(erb文件)中添加<%= javascript_include_tag 'js_file_name' %>
答案 2 :(得分:0)
添加到您的视图和
<%= javascript_include_tag 'js_file_name' %>
config / initializers / assets.rb
Rails.application.config.assets.precompile += %w(js_file_name.js)