Thursday, 19 June 2014

Javascript window resize listeners force you to double check your code

Working to my NextCharts HTML5 library made me to think more defensive when writing Javascript code. NextCharts library is used by NextReports Server inside its Dashboards section. Here, any dashboard can contain a number of charts and widgets.

Any chart / widget has a resize event defined in its code , like :

window.addEventListener('resize', resize, false); 

So, when the browser is resized, all charts and widgets are also resized.

The problems may start to appear when we change between dashboards. Visually I saw, sometimes , that the animation is not working. Looking for Javascript errors, I saw that in some place my canvas element was null. How can it be? I was just doing:

var canvas = document.getElementById(id);

Why is not the element id found?

And then it struck me: The resize event is registered for some charts/widgets and when we change the dashboard those listeners are still active, the browser notifies them about the event, but the components are not found inside the page anymore, so the canvas is null for them.

Because we do not know when to remove the resize listener for a specific component inside dashboard, the solution is to check for canvas null values in our javascript functions:

if (canvas == null) {
      return;
}
This is something you cannot think until you use your Javascript code under a big umbrella.

No comments:

Post a Comment