Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Page Specific Javascript

Javascript • Asked by Michael Victor

I just came across this article that talks about a gem that allows you to implement cleanly space specific javascript.

http://brandonhilkert.com/blog/page-specific-javascript-in-rails/

However, it was written in Feb 2014, does anyone know if there is now a better way to do this?


This is a really great question Michael. Do you have examples of what kind of Javascript you intend to run on specific pages? I can give you some generic advice, but it's always easier to understand with some examples.


We'll im looking at loading some elements via AJAX on page load on certain pages. I could check for the existence of certain elements and start making the AJAX calls but I'm guess there are simpler ways.

And I'm thinking that keeping the JS and the Rails code as separate as possible is generally a good idea.


That's actually what I would recommend doing. If you set up your JS to look for data-behavior tags like I covered in this episode you can load things into those tags.

The best way is not to really have page specific javascript, but instead to have these little widgets that can be reused anywhere by detecting things on the page. It'll keep the JS and Rails code very separate and the flexibility of making it not tied to specific pages helps a lot in the future.


I had to do something like this in a specific circumstance. The solution I used was to create a unique body class for each page with interpolation.
In HAML:
%body{:class => "#{controller_name}-#{action_name}"}

In ERB:
<body class="<%= controller_name %>-<%= action_name %>">

Then I can just use the unique controller/action_name class to as a JS hook.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.