Categories
Programming

Turbolinks and Vue: JavaScript Managing Memory

Turbolinks is a tool that is included in Rails project that renders each page change without actually changing the page in the browser. This helps to make the browsing feel faster and causes less flashing as you change pages.

Vue.js is a JavaScript framework to help build a user interface.

You could probably just impelment them together and forget about it, but I had a concern about memory leaks. As you move from page to page, normal page browsing destroys anything you’ve stored in a variable in JavaScript, but Turbolinks prevents the browser from deleting any variables (and usually, if you load a library such as jQuery, destroying and parsing the code takes time that is unnecessary). There is a lack of documentation on how to make these 2 libraries work together, and most places just say “disable Turbolinks in order to use Vue.js”.

I’m not sure that this is complete, but it’s probably better than nothing. My JavaScript solution is as follows:

(function() {
  var vue;
  $(document).on("turbolinks:visit", function() {
    // If the instance exists, destroy
    if (vue) vue.$destroy();
    vue = null;
  });

  $(document).on("turbolinks:load", function() {
    el = $("#myVue");
    if (el.length === 0) return
    vue = new Vue({
      el: el[0],
      data: {},
      // ...
  });
})();

If you have comments or tips on how to improve this, leave me a comment!

%d bloggers like this: