Fetch remote data with a local fallback and surface errors cleanly.
View the page source and read the Javascript code to see how it was done.
// Fetch with remote-first fallback to local file
(function loadTimeline() {
var sources = [
'https://raw.githubusercontent.com/kendawson-online/vantl/refs/heads/main/demo/assets/data/api-fetch-demo-data.json',
'../../../assets/data/api-fetch-demo-data.json'
];
function renderError(message) {
var el = document.querySelector('#api-tl');
el.innerHTML = '' + message + '
';
}
function tryFetch(url) {
return fetch(url, { cache: 'no-cache' })
.then(function (res) {
if (!res.ok) { throw new Error('HTTP ' + res.status); }
return res.json();
});
}
sources.reduce(function (attempt, url) {
return attempt.catch(function () { return tryFetch(url); });
}, Promise.reject())
.then(function (data) {
timelineFromData('#api-tl', data.nodes || data, { mode: 'horizontal', minWidth: 700 });
})
.catch(function (err) {
renderError('Failed to load timeline data from all sources.');
console.error(err);
});
})();