1

Long story short, I'll show the code.

some.html

<html><script src="some.js"></script></html> 

some.js

window.onload = () => console.log( "onload" ); (async (url, cb) => cb( await ( await fetch(url) ).json() )) ( "some.json", () => console.log( "in async" ) ); 

and some.html outputs:

onload in async 

I've done some works e.g. image loading in real fetch, so fetch().then() doesn't work for me.

Now my question is as title says, how can I let "onload" waiting for "fetch" complete?

5
  • Why does not fetch().then() work for 'you'? Commented Sep 14, 2019 at 12:55
  • window.onload = () => console.log( "onload" ); . that sets the onload handler function ... the rest is completely separate code Commented Sep 14, 2019 at 12:56
  • @MarkusZeller because I need to do some job after e.g. images loading complete, can then catch this? Commented Sep 14, 2019 at 13:04
  • how about something like pastebin.com/8jT4yPNL Commented Sep 14, 2019 at 13:04
  • @JaromandaX Cool thing! Would you please just write same text as an answer ? Commented Sep 14, 2019 at 13:07

1 Answer 1

10

What I think you are trying to achieve is the fetch starts before window.onload, but onload needs to wait for the fetch before doing anything else ...

const promiseOfSomeData = fetch("some.json").then(r=>r.json()).then(data => { console.log('in async'); return data; }); window.onload = async () => { let someData = await promiseOfSomeJsonData; console.log("onload"); }; 
Sign up to request clarification or add additional context in comments.

6 Comments

Well, I made a mistake, in this way onload triggers before all images loaded ... in fetch function I write some DOM operations, how can I trigger a function when page really completely loaded?
erm, I can only go by the code you posted, with the code you posted, this is correct, with your actual code, only you know - it seems window.onload is not the event you are looking for™ - though, window.onload triggers when the page is completely loaded (anything you "load" using fetch is NOT waited for by onload - but then, that's the whole point of this answer, isn't it)
Well I've tried several times today, none works. So is there any way to let "onload" waiting for "fetch"? Or I must fall back to httprequest?
I can tell you right now that console.log("onload"); won't happen until AFTER promiseOfSomeData is "complete" ... I don't know why you keep going on about "images" since nothing in your code suggests anything to do with images
If we wait for onload outside of window (eg. in iframe) - that method doesn't work
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.