How to use javascript et css efficiently for rails?

I had a lot of problems to cover my javascript and css files in my rails application. By definition, I mean:

How to work with java-script and CSS is used only on one page or on one controller?

I tried some solutions, but they were all complex and not very elegant:

  • I saw some tips like this: including my .js file directly in my .erb file, for example:

    <% content_for :head do %>
      <script type="text/javascript">
    <% end %>
    

    and then print it in the application layout. But that means making another request to the server to get the .js file. I think it’s important to stay with only one .js file and one .css file for the application created by the pipeline

  • I saw some other tips, such as testing if my HTML tag was present in the DOM using the method . length jquery. This all the same means testing on each page if a specific tag is present (knowing that it will be present on only one or two pages).

I found a solution that is easy to implement and, in my opinion, elegant.

+4
source share
2 answers

Requirements:

in your application layout change

<body>

to

<body class="#{controller_name}_#{action_name}">

The body will have a different class for each page. For example, in a blogging application using article_controller and an index action on this controller, the body would be:

<body class='article_index'>

CSS Overview

CSS . , (, #), SCSS:

body.article_index {
# CSS STYLE HERE
}

.

Javascript

jquery-readyselector. .ready(), script:

$('.article_index').ready(function () {
    alert("I'm on article#index !");
});

, turbolink.

turbolink. java- script , - - :

// accommodate Turbolinks
$(document).on('ready page:change', function() {
// STUFF
});

- ( ) ( ready, page:change), jquery-readyselector :

// accommodate Turbolinks
$('nav.nav').ready(function() {
// STUFF
});

.

, -.

+6

css/js , view ( ), layout :

#app/views/layouts/application.html.erb
<html>
   <head>
      <% if controller_name == "test" && action_name == "index" %>
         ...
      <% end %>
   </head>
</html>

-, , controller_name action_name - controller action .

-

Turbolinks

, , . :

$('nav.nav').ready(function() { //-> wrong syntax

Turbolinks, event Turbolinks javascript:

var nav_ready = function() {
   // do stuff here
};

$(document).on("page:load ready", nav_ready);
+1

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


All Articles