Selectize and Turbolinks

Jeroen Visser
Jeroen’s Personal blog
1 min readApr 7, 2016

--

So today, I was working on a new project, which is using Rails 5 (beta 3), the pre-release of the upcoming version of Rails. I was implementing Selectize.js. Rails 5 uses Turbolinks 2, which makes loading pages a lot faster. Turns out, Turbolinks doesn’t always play nicely with other libraries…

What Turbolinks does is when a user clicks a link, the page is fetched with XHR and the page’s <body> element is then replaced with the response’s. This makes sure the JS is only downloaded and executed once, and speeds up page loads a lot. Along with that, Turbolinks caches the content of the response, so when you go back in history or visit a similar URL, it’ll show the cached content (and in the case of a similar URL, fetch the new content and replace it as soon as the request finishes).

This caching might however cause some issues when you’re using libraries that change DOM, such as Selectize.js. If you’re using one of these, you’ll have to make sure to restore the elements before turbolinks caches the DOM. I did this by doing something like this:

$(document).on 'turbolinks:before-cache', ->
$('[data-selectize]').each ->
this.selectize.destroy()

This will make sure the DOM is restored to it’s original state before the cache is being saved, and thus preventing Selectize.js from rendering the same input twice.

--

--