简体   繁体   中英

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

I have multiple files in app/assets/javascripts, and to test, I have written in a file in this folder : test.coffee :

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

My question is as follows:

Why the javascript it loaded in all the pages I visit on my website, I know there are included in application.js but I think it is not optimized, no ?

What do you think about that ? Could you tell me an optimized method to make ajax calls in multiple pages but where are not included in all pages of the website ? Actually I do like that :

<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>

I put this part of code in a file and it is loaded only in one page put I think it is not clean... Otherwise I do like that :

$ ->
  # 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()
          }
        }

But like I have said on the top, it is loaded in all the website ...

Linguee helped me to write this question...

Thanks !

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

That is by design. Your views/layouts/application.html.erb loads javascript file application.js . If you go to app/assets/javascripts/application.js , you'll see instructions to load all of your assets. Since application.js is loaded on all of your pages (due to it being in the layout template), all your assets are loaded on all pages.

What you can do is create another "master" file. Say, app/assets/javascripts/application-with-custom-ajax.js and load your additional logic in it (and not load it in application.js ). Then you just have to make sure to include this alternate file instead of application.js on pages where you need the additional logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM