I'm using Turbolinks for the first time and not with Rails (I'm using Django).
REPRODUCTION
https://glitch.com/edit/#!/join/dc628a17-3ccd-47b4-9921-8fb332aaebb1
SOURCE CODE
index.html
:<html> <head> <script defer src="/js/index.js"></script> </head> <body> Text and NO <script></script>! </body> </html>
about.html
:<html> <head> <script defer src="/js/index.js"></script> <script defer src="/js/about.js"></script> </head> <body> Text and NO <script></script>! </body> </html>
index.js
:import Turbolinks from 'turbolinks' Turbolinks.start()
about.js
:function drawChart() { console.log("I will drawChart() here") } // drawChart() <--- this is commented on purpose here, with this it works! document.addEventListener('turbolinks:load', drawChart)
THE PROBLEM
If I start from page /index
and then navigate by link to /about
nothing happens!
If I now go back to /index
I can see in console the log: I will drawChart() here
. So the listener is working.
If I start (refresh on) from /about
instead it print in console the message so the listener turbolinks:load
is running the function drawChart()
on refresh.
WHAT I EXPECT AND WHAT I DID
I need the call to the function drawChart()
happens in the first navigation to /about
too.
So I thought of using a direct call in the file (drawChart()
, commented in the source code on this issue as you can see) and it works.
But I think this is not the good way to go, especially because if I go on /about
and refresh the page it's called two times!
It seems to me too hacky.
Isn't?
WAHT DO OTHER PEOPLE DO
- Same problem but his solution doesn't work for me: https://candland.net/rails/2019/03/13/rails-turbolinks-not-firing-js-on-load.html
I think the problem is that
turbolinks:load
is being fired beforeabout.js
is loaded. When Turbolinks renders a new page it will add any non-existent scripts to the<head>
and then trigger lifecycle events e.g.turbolinks:load
. In this case, it will not wait for everyscript
to load before triggeringturbolinks:load
. Here's what's probably happening:index.html
loads withindex.js
about.html
about.js
about.js
starts downloadingturbolinks:load
about.js
finishes downloading and executesBecause
turbolinks:load
was already triggered in 5. the callback inabout.js
won't be called until the next load.You may want to try including about.js at the bottom of the
<body>
ofabout.html
. Theturbolinks:load
listener will not be needed.Alternatively, try and include your JS in a single file, and perhaps use content of the page to determine when to call
drawChart
. For example: