Rails inline Javascript and Best Practices

后端 未结 5 1919
你的背包
你的背包 2021-02-14 07:54

I\'m kinda new to using Rails, and an app I am working on is progressing well - however I\'m looking though the generated HTML and noticed things like...



        
5条回答
  •  终归单人心
    2021-02-14 08:37

    Sometimes inline JavaScript is useful for critical, fast views (e.g., certain landing pages), or small snippets (e.g., Facebook SDK initialization, Analytics/Kissmetrics initialization scripts, etc.) where using no external libraries can speed up page load. For those cases, I recommend using a partial _facebook.js.erb inside layouts, and define a helper:

    module ApplicationHelper
      def facebook_tag
        content_tag :script, render(partial: 'layouts/facebook.js')
      end
    end
    

    Then, create the file _facebook.js.erb and include the inline JavaScript inside application.html.erb using the defined helper:

    <%= facebook_tag %>
    

    For any other case, such as the partials you mention that inline JavaScript, I recommend using unobtrusive JavaScript as other answers suggest.

提交回复
热议问题