Serving Web Content Adaptively to a Mobile or Tablet Device
Serving content depending on the device type is useful for improving a responsive website's performance. When latency is a bottleneck (e.g. over 3G networks), this solution can reduce the payload sent to the end user.
In this article, I will explain how to serve a different sized image depending on whether the user is on a mobile, or tablet device.
One solution I’ve found for this problem can be achieved with two pieces of Ruby community software, Nando Vieira's Browser for browser detection and Mark Evan's Dragonfly for on demand image processing.
Browser allows us to conditionally check, with the help of the HTTP Request Header, whether a request is being made from a mobile, or a tablet device.
Here are the steps and Ruby code necessary to serve content adaptively based on device type:
A Browser object can be instantiated if it has access to the HTTP Request Header, for example, in a Ruby on Rail's controller with a require "browser" line at the top:
@browser = Browser.new(request.headers["User-Agent"], accept_language: request.headers["Accept-Language"])
Boolean methods mobile? and tablet? are defined on the Browser object. For example, in a request made from a mobile device, these statements would return the following:
@browser.mobile? > true @browser.tablet? > false
Now, we can wrap this conditional logic around Dragonfly's on demand image processing (in a Ruby on Rails environment, this code would go in a view’s template); so a mobile device will get a 640x300 image, and a tablet will get a 1280x600 image:
if @browser.mobile? Dragonfly.app.fetch(:asset).thumb('640x300'); elsif @browser.tablet? Dragonfly.app.fetch(:asset).thumb('1280x600'); end
In the end, we send smaller payloads to devices that do not need a full resolution image, increasing performance over slow network connections.
If you would like to try a different methodology, Scott Jehl's Picturefill is also worth exploring.