Using WebShims with Rails Turbolinks

Keeping your HTML5 polyfills with Turbolinks

Update 13th Feburary 2016: The article below has largely been kept for reference only. At the time, I wasn't dealing with production Rails deploys and didn't do asset precomplation - for this, further steps are required. The entire process fully covered on the webshim-rails GitHub repository, so please follow the steps outlined there.


WebShims is a very handy library that provides HTML5 features that are otherwise not natively by the browser via JavaScript & CSS. My most frequent use is for forms: for example, it provides a date picker for an <input type="date" /> tag.

Recently, I've been starting out a small Rails 4 app, which comes with Turbolinks enabled by default. For those who don't know, Turbolinks replaces page content when you click on a link, instead of loading a page in full. A brilliant introduction to Turbolinks is RailsCasts Episode 390, which is free to view.

My app had a simple ActiveRecord model with a date field, and I wanted to represent this field on the form with a date field. I added this via Rails' date_field helper, and I wanted to polyfill this field. For ease, I added the webshims-rails gem, which includes the relevant libraries - it is also possible to add WebShims manually. Choosing to use CoffeeScript, I then added the relevant lines to my application.js.coffee as instructed on the gem's readme.

Loading my form, the polyfills work perfectly! But when I visited it from my index action, I found it suddenly didn't work until I pressed the refresh button.

Thankfully, the solution is very simple - I just need to call the $.updatePolyfill() function on the page:load event. Filling this in, my CoffeeScript now looks like this:

# ... all other required scripts
#= require jquery
#= require webshims/extras/modernizr-custom
#= require webshims/polyfiller
#= require_tree .

$.webshims.setOptions("basePath", "/assets/webshims/shims/")
$.webshims.polyfill()

$(document).on "page:load", ->
    $(this).updatePolyfill()

* As an aside, I know there are more brackets here than necessary for CoffeeScript, but I often like to make my function parameters clear.

Now the form elements have their polyfills applied, regardless of whether or not the form is visited via a link on the application.

A sample application.js.coffee can be found here as a gist, and as you're more than welcome to chip in with any suggestions and improvements.

comments powered by Disqus