Why should javascript not be displayed if it is used only on certain pages?

In his response, Richard Peck writes:

Unobtrusive JS

Something else to consider (you've already done this) is that you really need to use unobtrusive javascript in your application.

Unobtrusive JS basically means that you can abstract your “bindings” from your page to your Javascript files in the asset pipeline. There are several important reasons for this:

  • Your JS can be loaded on any desired page (this is DRY)

  • Your JS will be in the backend of your application (will not pollute the views)

  • You can use JS to populate the various elements / objects that you want on the screen.

It is always recommended to put JS in separate files, including in the views that you configure for a lot of clutter in the line

This brings me to the following question:

If I use only a script on a specific page, why should I upload it to each page? Isn't that against DRY? Perhaps I do not understand how the Rails pipeline works.

+4
source share
2 answers

Rails conveyor

Not a Rails pipeline, unobtrusive JS is the standard programming pattern.

Extracting JS from the page ("inline") into an external file clears the page, nothing more.

, JS . , , . , admin.js application.js.


Rails , JS , precompile . - application.js - , , .

config.assets.precompile hook - , , :

# config/application.rb
config.assets.precompile << %w(admin.js cart.js etc.js)

manifest.js Sprockets 4+ ( ), commit .

, ( dev - ) admin.js , , . ; public/assets.

, , :

# app/views/layouts/application.html.erb
<%= javascript_include_tag :application, (:admin if [[condition]]) %>

or

# app/views/layouts/admin.html.erb
<%= javascript_include_tag :admin %>

, , .

, .

+2

script , Turbolinks. Turbolinks javascript . , script application.js, js- ( application.js) , . Rails, Turbolinks ajax (, javascript ), javascript, , sorta DRY, , .

script , ?

, Turbolinks Angular\Backbone\ javascript : javascript html , html javascript .

+1

Source: https://habr.com/ru/post/1665262/


All Articles