How to properly work with jQuery in Rails 3.1 asset pipeline?

前端 未结 2 943
名媛妹妹
名媛妹妹 2021-02-19 02:12

I\'m working on a hobby app and using some jQuery. The results are fine at the moment, but I\'m a jQuery noob and I assume that there are some significant improvements that I ca

2条回答
  •  情书的邮戳
    2021-02-19 02:51

    I'll attempt to answer some of these for you. You only really want 1 document ready call per page, but it doesn't matter if you have multiples. Whatever is contained within them is going to be the code that executes once the DOM has been loaded into the browser. Rails won't do anything magical with the javascript, it will stay the same as what you write in your files. Rails won't compile the javascript code in a funky way, for production environments it may minify it, but the actual code will remain mostly the same. This is executed by the browser - not the server.

    You are not instantiating 2 instances as jQuery is only loaded once, then referenced. The $(document).ready() call is just a function essentially, nothing more.

    The model-specific jquery files can be used in conjunction with Ajax in a rails app. So you can have files like 'create.js.erb' which is actually a javascript file you can pass rails actions into. If you want to fire some specific code after a create/delete post then you can use files like this to do that, you just have to respond the javascript in your rails controller - but this is going a bit deeper that you mean to by the looks of your question above.

    The main thing to remember is jquery is just javascript and javascript gets run by the browser - on the front end without any dynamic integration, is will always run on the client side and jquery is fantastic mainly for DOM manipulation.

    Hopefully that will clear some stuff up!

提交回复
热议问题