Michael Michael - 1 month ago 12
HTML Question

Prevent from executing previous JavaScript with turbolinks and highcharts //LazyHighCharts

I'm using turbolinks 5 and rails 5 version and with newest Highcharts. T

LazyHighCharts provides functionality for Turbolinks5 and wraps chart building javascript with

(function() {
document.addEventListener("turbolinks:load", function() {
//code
window.chart_my = new Highcharts.Chart(options);
});
})()


But when I'm navigating away from page where graph was loaded previously with turbolink, I got error on newly loaded page.

Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13


Looks like that all previous javascript which was loaded with
"turbolinks:load"
are reevaluating and causing highchart to throw error, because in new DOM there's no element to which that highchart graph is renderedTo.

I tried to unbind
"turbolinks:load"
event from document, but it doesn't work. It reevaluates it anyway.

Thought about solution to fork LazyHighCharts, to rewrite layout_helper, so javascript is outputed after dom element, but this would slow the page so the page flow would be

loaded-dom (graph)
evaluate js (sync)
-->
loaded-dom (graph)
evaluate js (sync)
--->
loaded-dom (graph)
evaluate js (sync)
etc. and it would slow down page load i Guess.

Maybe guys here have some solution to this problem.

Answer

Made a pull request to lazy_high_charts

document.addEventListener("turbolinks:load", function(e) {
  // code
  e.target.removeEventListener(e.type, arguments.callee);
});
Comments