So I'm really not a JS guy in the slightest, but wanted to basically render a CSV as table on my Jekyll site - I have this working with the following script.
Only problem is it never seems to load the table first time, I need to click refresh in the browser for it to appear - does anyone have any ideas as to what could be the cause of this?
<script>
window.onload = function() {
with(new XMLHttpRequest()) {
onreadystatechange = cb;
open('GET', 'https://raw.githubusercontent.com/clintjb/A350-Tracking/main/flight_data_a350.csv', true);
responseType = 'text';
send();
}
}
function cb() {
if (this.readyState === 4) document.getElementById('A350')
.innerHTML = tbl(this.responseText);
}
function tbl(csv) {
return csv.split('\n')
.map(function(tr, i) {
return '<tr><td>' +
tr.replace(/,/g,'</td><td>') +
'</td></tr>';
})
.join('\n');
}
</script>
<table border="0" style='font-size:50%' id="A350"></table>
I was not able to recreate the issue on my machine. Your code worked fine for me, at least in chrome, but one thing you could try is using fetch instead of XMLHttpRequest. both worked for me
That would look something like the following
<script>
fetch('https://raw.githubusercontent.com/clintjb/A350-Tracking/main/flight_data_a350.csv'
).then((response) => {
return response.text();
}).then((text) => {
document.getElementById('A350').innerHTML = tbl(text);
})
function tbl(csv) {
return csv.split('\n')
.map(function (tr, i) {
return '<tr><td>' +
tr.replace(/,/g, '</td><td>') +
'</td></tr>';
})
.join('\n');
}
</script>
<table border="0" style='font-size:50%' id="A350"></table>
So all the solutions (including my first proposal) actually worked. The issue in the end was actually a strange bug in the template used on the Jekyll site.
If you went directly to the page it rendered fine, if you refreshed it rendered fine - was only going via the menus which would than cause the rendering issue.
Due to this I changed the approach and used a GitHub actions to push the file each day - with the CSV in the same repo as the (e.g. like in _data/my_file.csv) you can access the data when the site builds as
{{ site.data.my_csv }}