The loadExternalScript() method allows designers to load an external script to the <head> section of the portal. The loadExternalScript() method takes an URL as input.
For example:
await loadExternalScript("https://cdn.jsdelivr.net/npm/chart.js");
The loadExternalScript() method does not work in the WYSIWYG editor. If the loadExternalScript() method works when editing the Custom component, save and publish the component anyway.
The following full example first calls the List maps web service using the API access method.
With the results, the script uses Chart.js to create a pie chart. The pie chart shows the proportion of each value of a metadata key across all maps. This metadata key is the value of the metadataComparator variable.
HTML:
<div>
<canvas id="categoryChart" width="400" height="400"></canvas>
</div>
JavaScript:
// Defines the metadata key for comparison
const metadataComparator = "Category";
async function fetchFluidTopicsData() {
// Load Chart.js using loadExternalScript
await loadExternalScript("https://cdn.jsdelivr.net/npm/chart.js");
// Initialize Fluid Topics API
const FTAPI = await new window.fluidtopics.FluidTopicsApi();
FTAPI["Ft-Calling-App"] = "ft-page-designer";
try {
// Fetch maps data
const response = await FTAPI.get('/api/khub/maps');
const data = response;
// Prepare a dictionary to count categories
const categoryCounts = {};
// Extract categories from the data
data.forEach(item => {
const metadata = item.metadata;
const categoryMeta = metadata.find(m => m.key === metadataComparator);
if (categoryMeta) {
const category = categoryMeta.values[0];
categoryCounts[category] = (categoryCounts[category] || 0) + 1;
}
});
// Convert the category count dictionary into data for the chart
const labels = Object.keys(categoryCounts);
const counts = Object.values(categoryCounts);
// Create pie chart
const ctx = document.getElementById('categoryChart').getContext('2d');
new Chart(ctx, {
type: 'pie',
data: {
labels: labels,
datasets: [{
label: 'Categories',
data: counts,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Pie chart of document categories'
}
}
},
});
} catch (error) {
console.error("Error fetching data:", error);
}
}
(async function() {
await fetchFluidTopicsData();
})();
This creates the following: