Fellow Stranger
Fellow Stranger

Reputation: 34013

Separate js-code for desktop and mobile visitors in Rails

I have a Rails app that have 50 or so js-functions organized in separate files, in the app/assets/javascripts folder.

I'm now starting to remake certain pages for mobile visitors, detecting them in the controller with the method:

def mobile_agent?
  request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(iPhone|iPod|BlackBerry|Android)/]
end 

and serving them separate views that content-wise are completely different from the "desktop" views.

I don't want the javascript files (and it's code) used for the desktop visitors to load for the mobile visitors, and vice versa.

One way could be to skip loading the js-assets alltogether with

<%= javascript_include_tag "application" unless mobile_agent? %>

but where do I then put my mobile js-files?

Or any better suggestions?

Upvotes: 1

Views: 400

Answers (1)

manishie
manishie

Reputation: 5322

You can have as many manifest files as you want. Just put them in /app/assets/javascripts and they will be compiled automatically. You can have:

mobile.js:

//= require sharedjs
//= require mobilejs

desktop.js:

//= require sharedjs
//= require desktopjs

And then in your layout file, something like:

<%= javascript_include_tag "mobile" if mobile_agent? %>
<%= javascript_include_tag "desktop" unless mobile_agent? %>

Upvotes: 3

Related Questions