Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turbolinks loads Javascript multiple times

I'm using Turbolinks 2.5.3 and I have a script tag at the bottom of the home page.

<script>
  $(document).ready(function() {
    alert('hello');
  });
</script>

For every page on the site, I run the following JS:

Turbolinks.pagesCached(0);

If I visit the home page, the alert appears once. If I press the back button then forward button on my browser the home page will load, and now two alerts appear. If I repeat this process again, three alerts will appear.

Here's my question:

Why is Turbolinks caching the page when I explicitly told it not to. Does it have to do with Turbolinks transforming the document ready event listener? How do I fix this so it only loads once every time?

like image 588
thank_you Avatar asked Oct 30 '22 20:10

thank_you


1 Answers

use turbolinks:load

<script>
  $(document).on('turbolinks:load',function() {
    alert('hello');
  });
</script>
like image 138
Bartłomiej Gładys Avatar answered Nov 11 '22 05:11

Bartłomiej Gładys