An under-the-hood change to the responsive function

Written by Richard, on 23rd December 2020

For the version 5.27 release, there has been an under-the-hood change to the responsive function.

Currently, this function makes use of the window.onresize event to be notified of changes to the window size (as well as being triggered initially by RGraph itself to correctly configure the view to start with).

Using this event is suboptimal as it can fire many times per second when the screen or browser window is being resized therefore slowing down the whole page and any JavaScript that is running at the time.

Now, however, the responsive function has been changed to use dynamically created media queries by way of the Window.matchMedia function. These are available in all of the browsers that RGraph works with except for Internet Explorer 9 - whose market share is negligible. The code to add a media query to your page using standard JavaScript looks like this:

var mediaQuery = window.matchMedia('screen and (min-width: 600px) and (max-width: 950px)');
mediaQuery.addListener(function (e)
{
    if (e.matches) {
        // ...
    }
});

Obviously what RGraph does is a little different to integrate it into the RGraph codebase, but it's largely the same. You can see the media query on the first line in red - normally with CSS media queries the minimum screen width wouldn't need to be specified but here it does. RGraph handles this for you though so you just need to give the maximum screen size.

Then, after having been created, a listener function is added for when this query is matched. This function is what takes care of resizing and reconfiguring the chart on the page.

Are there any changes to the usage of the responsive function?

The usage of the responsive function hasn't changed so in terms of making use of the new code there's nothing that you have to do differently (technically that's not true - the order of the screen sizes should be reordered from largest to smallest however RGraph will do this for you so you don't have to change your code).

Examples of using the responsive function can be found in the demos. Remember that there's no change from your point of view so you won't see any difference when version 5.27 is released. You can read more about the responsive function on the documentation page.