Add a loader to your chart
In this tutorial, we will learn how you can add a loader to your chart using various lifecycle events of muze. Loaders are very essential when you are visualizing large number of data points in the chart and a considerable amount of time will take to load the data and render the chart.
Brief intro to muze lifecycle event
Muze provides various lifecycle events that you can tap into for dispatching various actions.
Refer to the API documentation for details about available lifecycle events.
You can tap into any of these events by using once method of canvas.
canvas.once('afterRendered').then(fn);
Add a loader
Create a div:
<div id="loader"></div>
Add css styles and animation to the loader element,
#loader {
position: absolute;
border: 10px solid #f3f3f3; /* Light grey */
border-top: 10px solid #3498db; /* Blue */
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
Using canvas.animationend
to add the loader in the chart
Initially, we keep the chart hidden:
#chart {
visibility: hidden;
}
Now, we hook into afterRendered
event to show the chart and hide the loader.
canvas.once("afterRendered", () => {
document.getElementById("chart").style.visibility = "visible";
document.getElementById("loader").style.visibility = "hidden";
});
Complete Code
<div id="loader"></div>
<div id="chart"></div>
#chart {
width: 800px;
height: 550px;
visibility: hidden;
}
#loader {
position: absolute;
border: 10px solid #f3f3f3; /* Light grey */
border-top: 10px solid #3498db; /* Blue */
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
const { muze, getDataFromSearchQuery, env } = viz;
const data = getDataFromSearchQuery();
const canvas = muze
.canvas()
.data(data)
.rows(["Close"])
.columns(["Date"])
.title("MSFT Stocks from 13/3/1986 TO 8/1/2020")
.subtitle("A line chart with 10,000 data points")
.config({
axes: {
x: {
nice: false,
},
y: {
tickFormat: (val) =>
`$${val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`,
},
},
})
.mount("#chart");
canvas.once("afterRendered", () => {
document.getElementById("chart").style.visibility = "visible";
document.getElementById("loader").style.visibility = "hidden";
});