1👍
Using inline javascript is a bad practice since you mix behaviour and content.
Using inline javascript with Turbolinks is just plain stupid – Turbolinks essentially turns your app into a persistent one page app you get all kinds of weird timing issues do the fact that your scripts may not be run until turbolinks appends the new page to the DOM. By then the the page:change
event may have already have been fired.
This is why it only runs when you refresh the page vs when Turbolinks loads the page.
The fault isn’t Turbolinks – it’s your own. Put on the big boy pants and move that javascript into external files.
Added;
There are basically two approaches to creating widgets such as graphs that need external data. This is a generic sketch and in no way related to your question and whatever graph framework you are using.
Data attributes:
function Graph(data, el){}
if ($("#graph").length) {
var data = $('#bar>li').map(function(i,el){
return $(el).data() }
).toArray();
$("#test").text( JSON.stringify(data) );
Graph(data, $("#graph"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="bar">
<li data-x="1" data-y="2">A</li>
<li data-x="2" data-y="3">B</li>
<li data-x="3" data-y="4">C</li>
</ul>
<pre id="test"></pre>
Ajax:
if ($("#graph").length) {
var promise = $.getJSON('/foo.json');
promise.then(function(data){
return $.map(data, function(item){
return {x: item.foo y: item.bar };
});
});
promise.done(function(data){
Graph($("#graph"), data);
});
}