The DOMContentLoaded event: How to use it

Share RGraph:   Share or Like RGraph on Facebook!

An example of using RGraph in conjunction with the new DOMContentLoaded event. The new event can speed up the creation of your charts without you having to wait for the entire page to load.

Waiting for onload event...

These images are here to pad the page and slow down loading so that the window.onload event is slowed. This makes the difference far more visible.

[No canvas support]

The DOMContentLoaded event is an extremely useful event and can make a big impact on the performance of your pages, hence this example. The DOMContentLoaded event fires when the pages HTML and scripts have loaded, but not necessarily any images or CSS. This can make a big improvement on the apparent speed of your page(s).

You can read more about the DOMContentLoaded event on the Mozilla site here.

function createChart(func)
    window.addEventListener('DOMContentLoaded', function ()
        // Create your chart here
    }, false);

Browser support

The DOMContentLoaded event is supported by the following browsers:

The jQuery ready() event

The jQuery ready() event can be used to create your charts. This primarily uses the DOMContentLoaded event and falls back to the window.onload event when the DOMContentLoaded event is not available. You would use it like this:

    window.onload = (function ()
        // Create your chart here

Because of the proliferation of jQuery you may already be using it - in which case it's a simple matter of adding a function call to it that creates your chart.

See also

You might also be interested in asynchronous chart creation as an alternative.
© Copyright Richard Heyes 2008-2017