javascriptwindow-load

window.onload event does not seem to be working


Here is my code for onload event:

let statElements = []; 
let data = [];
const dailyBtn = document.getElementById("daily");
const weeklyBtn = document.getElementById("weekly");
const monthlyBtn = document.getElementById("monthly");
async function fetchDataAndProcess() {
    try {
        const response = await fetch("data.json");
        data = await response.json();

        const sections = document.querySelectorAll("section.card");

        sections.forEach((section, index) => {
            const title = data[index].title.toLowerCase();
            const h2Element = section.querySelector(`h2.${title}-stats`);
            const pElement = section.querySelector(`p.${title}-stats`);

            statElements.push({
                h2: h2Element,
                p: pElement
            });
        });
    } catch (error) {
        console.error("Error fetching or processing data:", error);
    }
}
fetchDataAndProcess();
function weekly() {
    statElements.forEach((element, index) => {
        element.h2.textContent = `${data[index].timeframes.weekly.current}hrs`;
        element.p.textContent = `Last Week - ${data[index].timeframes.weekly.previous}hrs`;
    });
    weeklyBtn.style.color = "white";
    monthlyBtn.style.color = "hsl(235, 45%, 61%)";
    dailyBtn.style.color = "hsl(235, 45%, 61%)";
}
window.onload =  weekly;

Basically what this is supposed to do is retrieve h2 and p elements from each section and set their textcontent to the data in the json object. The problem I am having is sometimes, it is working, sometimes, it seems not to have been executed because I don't see the contents of my h2 and p have been filled. So, I am wondering if it is because of using async function or using onload event. Maybe i should use something else?

I changed the window event to DOMContentLoaded, nothing changed. I changed the window event by adding event listener load, still the problem did not disappear.


Solution

  • Since fetchDataAndProcess() is async, you'd want to wait for it to finish.

    Move the call to it underneath the function weekly() invocation, then chain them with e.g. .then() (unless top-level await is available):

    fetchDataAndProcess().then(weekly);