All posts
Liferay · 12 min read · Jul 17, 2026

Getting Data into Chart Fragments Without Breaking the Page

Chart fragments fetching and rendering data on a portal page

Wrapping a charting library in a fragment takes an afternoon. The first version works, looks good in a demo, and is the version most people ship. The problems appear on a real dashboard page, where several instances coexist, an editor is changing configuration live, and the data is coming from somewhere that can be slow, empty, or forbidden.

Load the library once, not once per instance

The first thing that breaks is the most predictable. Each fragment instance includes markup that adds the library, so a page with five charts requests it five times, and whichever instance runs first wins a race the others do not know they are in.

javascript
// One promise per page, shared by every instance.
window.__chartLib = window.__chartLib || new Promise((resolve, reject) => {
    if (window.ChartLibrary) return resolve(window.ChartLibrary);

    const script = document.createElement('script');
    script.src = LIBRARY_URL;
    script.onload = () => resolve(window.ChartLibrary);
    script.onerror = reject;
    document.head.appendChild(script);
});

// Every instance awaits the same promise.
window.__chartLib.then((lib) => renderChart(lib, element, config));
A cached promise makes concurrent instances safe without coordination between them.

The same pattern applies to anything shared - a locale bundle, a date library, a theme palette. The rule is that a fragment may depend on a shared resource but must never assume it is the only one loading it.

Every instance needs its own identity

Fragment markup is duplicated for every placement, so any fixed element id appears several times on the page. The symptom is distinctive and confusing: several charts render into the same container, or four of five appear blank, depending on ordering.

Scope everything to the fragment's own root element rather than to the document. Look up children relative to that root, store instance state on the element itself, and never reach for a global lookup by id. This single habit removes an entire category of multi-instance bugs.

Three places the data can come from

SourceGood forWatch out for
Values typed into configurationSmall fixed series, demos, illustrative chartsBecomes unmaintainable past a handful of points
A REST call at render timeLive business data, the usual caseLatency, permissions, page size, error states
Content mapped from the pageEditorially curated figuresRequires the data to exist as content
Most real dashboards use the second, and inherit all of its failure modes.

The page size trap

This one is quiet and costs the most credibility. A chart fetches from a REST endpoint, receives the default page of results, and renders a perfectly convincing chart of the first twenty rows out of four thousand. Nothing errors. The chart is simply wrong, and it stays wrong until somebody checks a total against another system.

Always read the returned count rather than the length of the array you received, and decide explicitly what the chart does when there is more data than it fetched. Aggregating client side only works for genuinely small sets; beyond that the aggregation belongs on the server, which usually means a purpose-built endpoint rather than the generated CRUD API that returns rows.

This is worth stating plainly because it is the point at which many dashboard projects go wrong: charts want grouped, aggregated data, and record APIs return records. Deciding where that aggregation happens is an architecture decision, not a detail to solve in the fragment.

Behave properly inside the page editor

While someone is configuring a chart, the fragment re-renders on every change. Without cleanup, each render adds a new chart instance over the previous one, leaks the old canvas, and leaves timers running.

javascript
function renderChart(lib, root, config) {
    // Tear down the previous instance before creating a new one.
    if (root.__chart) {
        root.__chart.destroy();
        root.__chart = null;
    }

    root.__chart = new lib.Chart(root.querySelector('canvas'), config);
}
Destroy before create - the difference between a smooth editor and one that slows to a halt.

Fetching deserves the same treatment. Re-requesting data on every keystroke while someone types into a configuration field is both slow and unkind to the server; debounce the fetch, and cancel any request that a newer one supersedes.

Follow the theme instead of fighting it

Hardcoding a palette guarantees that the chart looks correct in exactly one theme and wrong in every other, including dark mode. Reading colours from the theme's own custom properties costs a few lines and means the chart follows the site automatically, including when the site is restyled later.

It also solves the configuration question raised by colour: rather than exposing arbitrary colour pickers, expose a choice between named theme palettes. Editors get control, the pages stay on-brand, and you get a finite set of appearances to test.

Decide what the empty and broken states look like

  • No data returned: an explicit empty message, never a blank rectangle that reads as a failure.
  • Request failed: a short message that says the data could not be loaded, without exposing internals.
  • Not permitted: the same as empty, because a user should not learn what they cannot see.
  • Still loading: a placeholder of the chart's final height, so the page does not jump when it arrives.
  • Partial data: either state clearly that it is a sample, or do not render a chart at all.

The loading placeholder is worth the small effort. Charts are usually the tallest thing on a dashboard, so a chart that appears late pushes everything below it down the page at the moment the user is trying to click something.

Charts are invisible to some of your users

A canvas is an opaque image to a screen reader, and a page whose key information exists only inside one is unusable for part of its audience. The pragmatic answer is not to abandon charting but to make the underlying numbers available - a visually hidden table, a summary sentence stating the trend, or a link to the data behind it.

It also helps everyone else. A chart that can state its own headline in one sentence is usually a chart that has been thought through, and the sentence is frequently what the reader wanted in the first place.

Conclusion

Chart fragments fail in multiples, not individually. Share the library through one cached promise, scope every instance to its own root, read the total rather than trusting the page you received, tear down before re-rendering so the editor stays usable, take colours from the theme, and design the empty, loading and failed states as deliberately as the success one. The charting library was never the hard part - the page around it was.

Contact

Let’s connect

Have a Liferay or Backend project you’d like to talk through? Fill in the form and I’ll get back to you.

Book Calendar