1

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.

2 Answers2

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