AmCharts.ready is not ready when loaded asynchronously
-
20-12-2019 - |
Question
Initially I put all AmChart configs in AmCharts.ready is everything worked fine.
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script src="amcharts/serial.js" type="text/javascript"></script>
<script>
AmCharts.ready(function() {
console.log("this works");
/* Other configs */
})
</script>
Somehow it stops working when I introduce RequireJS as instructed in amCharts meets requireJS. Whatever code inside AmChart.ready's callback will not be executed. (Oddly it was executed one time during the debugging)
Solution
After a few tests I realized AmChart.ready only pushes the callback into the onReadyArray
which is later popped for execution after the window.load/onload event. In other words, if AmChart is loaded after window.onload event, AmChart.ready is useless. My workaround is as followed:
<script>
configChart = function() {
/* Create charts stuff */
};
if (AmCharts.isReady) {
configChart();
} else {
AmCharts.ready(configChart);
}
</script>
OTHER TIPS
Still doesn't work in newer versions (version 3.14.1 at this time), but what fixes it is calling the handleLoad
method manually:
AmCharts.handleLoad();
Calling it multiple times doesn't seem to do any harm, either.
Because I load in charts asynchronously, I needed to manually set "AmCharts.isReady = true;" before calling my AmCharts functions. For example:
var chartData1 = [];
function generateChartData() {
...
}
function createStockChart() {
...
}
if ($('.amChartDivExists').length > 0) {
AmCharts.isReady = true;
generateChartData();
createStockChart();
}