To make the dollar rates load faster and enhance the user experience, you can initiate the data fetching process earlier, such as in the <head> section of your HTML or immediately when the DOM is ready. You can achieve this by using the DOMContentLoaded event instead of window.onload, which waits for all content, including images and stylesheets, to be loaded before running the script. Here's how you can modify your code to do that:
async function fetchDollarRates() {
try {
const response = await fetch('https://api.bluelytics.com.ar/v2/latest');
const data = await response.json();
document.getElementById('blueBuy').innerText = `$ ${data.blue.value_buy}`;
document.getElementById('blueSell').innerText = `$ ${data.blue.value_sell}`;
const lastUpdate = new Date(data.last_update);
const now = new Date();
const timeDiff = Math.floor((now - lastUpdate) / 60000);
let timeText;
if (timeDiff < 1) {
timeText = "Actualizado hace menos de un minuto";
} else if (timeDiff === 1) {
timeText = "Actualizado hace 1 minuto";
} else if (timeDiff < 60) {
timeText = `Actualizado hace ${timeDiff} minutos`;
} else {
const hours = Math.floor(timeDiff / 60);
const minutes = timeDiff % 60;
if (minutes === 0) {
timeText = `Actualizado hace ${hours} ${hours === 1 ? "hora" : "horas"}`;
} else {
timeText = `Actualizado hace ${hours} ${hours === 1 ? "hora" : "horas"} y ${minutes} minutos`;
}
}
document.getElementById('timestamp').innerText = timeText;
} catch (error) {
console.error('Error fetching dollar rates:', error);
document.getElementById('blueBuy').innerText = 'Error loading rates';
document.getElementById('blueSell').innerText = '';
document.getElementById('timestamp').innerText = '';
}
}
// Change to DOMContentLoaded event
document.addEventListener('DOMContentLoaded', fetchDollarRates);
Notes:
-
DOMContentLoaded: This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Therefore, your function will be executed as soon as the document is ready, providing faster feedback to the user.
-
Error Handling: I added a try-catch block around the fetch call to handle any potential errors that might occur while fetching data from the API. This avoids breaking the rest of your UI in case of an error.
-
Loading Indicator (Optional): You may consider showing a loading indicator (like a spinner or a simple "Loading..." text) while the rates are being fetched. This can be specified before calling fetchDollarRates, making it clear to users that data is being loaded asynchronously.
Optional Loading Indicator Example:
<div id="loading" style="display: none;">Loading...</div>
<div id="blueBuy"></div>
<div id="blueSell"></div>
<div id="timestamp"></div>
<script>
async function fetchDollarRates() {
document.getElementById('loading').style.display = 'block'; // Show loading indicator
try {
const response = await fetch('https://api.bluelytics.com.ar/v2/latest');
const data = await response.json();
document.getElementById('blueBuy').innerText = `$ ${data.blue.value_buy}`;
document.getElementById('blueSell').innerText = `$ ${data.blue.value_sell}`;
const lastUpdate = new Date(data.last_update);
const now = new Date();
const timeDiff = Math.floor((now - lastUpdate) / 60000);
let timeText;
// Calculate timeText as before ...
document.getElementById('timestamp').innerText = timeText;
} catch (error) {
console.error('Error fetching dollar rates:', error);
document.getElementById('blueBuy').innerText = 'Error loading rates';
document.getElementById('blueSell').innerText = '';
document.getElementById('timestamp').innerText = '';
} finally {
document.getElementById('loading').style.display = 'none'; // Hide loading indicator
}
}
document.addEventListener('DOMContentLoaded', fetchDollarRates);
</script>
You can place the loading indicator HTML somewhere in your webpage, and it will help provide visual feedback while the data is being fetched.