为什么app/assets/javascripts中的coffee文件都加载到所有文件中了?

Why coffee files in app/assets/javascripts are loaded in all the files?

我在 app/assets/javascripts 中有多个文件,为了测试,我在此文件夹中的一个文件中写入: test.coffee :

$ ->
  $(document).ready ->
    alert("Hey");

我的问题如下:

为什么 javascript 它加载在我访问我网站的所有页面中,我知道 application.js 中包含但我认为它没有优化,不是吗?

你怎么看? 你能告诉我一个优化的方法来在多个页面中进行 ajax 调用,但网站的所有页面中没有包含哪些地方? 其实我很喜欢 :

<script type="text/javascript">
  $(document).on('keyup', 'input#field_seller_name', function(e){
    if(e.keyCode == 13 && $(this).val() != ""){
      $.ajax({
        url: '/field_sellers/' + $(this).parent().parent().data('field_seller_id'),
        type: 'PUT',
        dataType: 'script',
        data: {
          field_seller: {
            name: $(this).val()
          }
        },
        error: function(result){
          alert(result.responseText);
        }
      });
    }
  });

</script>

我将这部分代码放在一个文件中,它只在一页中加载,我认为它不干净... 否则我喜欢那样:

$ ->
  # This is for CREATE an new type_material by press enter touch with input in focus
  $(document).on 'keyup', '#name_new_type_material', (evt) ->
    if evt.keyCode == 13
      $.ajax '/type_materials',
        type: 'POST',
        dataType: 'script',
        data: {
          field_type_user: {
            name: $(this).val()
          }
        }

但是就像我在顶部所说的那样,它已加载到所有网站中...

Linguee 帮我写了这道题...

谢谢!

Why coffee files in app/assets/javascripts are loaded in all the files?

这是设计使然。您的 views/layouts/application.html.erb 加载 javascript 文件 application.js。如果您转到 app/assets/javascripts/application.js,您将看到加载所有资产的说明。由于 application.js 已加载到您的所有页面上(因为它位于布局模板中),因此您的所有资产都已加载到所有页面上。

您可以创建另一个 "master" 文件。比如,app/assets/javascripts/application-with-custom-ajax.js 并在其中加载您的附加逻辑(而不是在 application.js 中加载)。然后你只需要确保在你需要额外逻辑的页面上包含这个替代文件而不是 application.js