I'm currently writing a project that will need to fetch data from outside. My approach is when the event of DOMContentLoaded
is fired, I will begin to fetch the data. But I'm kind of stuck on whether I should use the event DOMContentLoaded
on window
object or on document
object. What are the differences and which is the better one?
My code below:
async function getProducts() {
try {
const result = await fetch('./products.json');
const data = await result.json();
return data ;
} catch (error) {
console.log(error);
}
}
Should I use this one below:
window.addEventListener('DOMContentLoaded', () => {
getProducts().then(//code that will render out the data on my web page);
});
Or should I use this one below:
document.addEventListener('DOMContentLoaded', () => {
getProducts().then(//code that will render out the data on my web page);
});
What are the differences and which approach is more appropriate?
I've seen this https://stackoverflow.com/questions/588040/window-onload-vs-document-onload
but I still cannot figure out my question.