I'm making a website in which I need to have a fetch request occur while the page is loading, otherwise it slows things down later. Is there a way to do this, as what normally happens is that this request is triggered through a button push, but I'd like to have it occur as the page loads.
Asked
Active
Viewed 1,245 times
2 Answers
0
Fetch is by itself async, so there is no problem in using it while page is loading. Just call it directly, like so
<script>fetch('link').then(response => {}).catch(error => {})</script>

AidOnline01
- 712
- 7
- 19
0
Add fetch inside your onload:
window.onload = () => {
fetch('https://jsonplaceholder.api').then(r=>r.json()).then(data =>
{
console.log(data);
//use data
});
};
Based on your use case you can use other events too

Tushar Shahi
- 16,452
- 1
- 18
- 39