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

前端 未结 2 956
名媛妹妹
名媛妹妹 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!

    0 讨论(0)
  • 2021-02-19 03:14

    1) Compilation: Rails assets pipeline just combines all javascript files in one big file.

    2) jquery is only loaded once, you are having multiple $(document).ready functions, but that is not a problem

    3) Rails does not do anything with the call, and jQuery can safely handle more of those blocks per page.

    4) You call it a model-specific .js, I would rather call it controller-specific. You group functionality together that belongs together. Whether the thing that ties them together is a controller or a model really does not matter. We split our js up in separate files to make it more manageable.

    5) In development the assets are compiled on every request, in production it is done only once. Also in production it could be minified and compressed.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题