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?

NotUser9123
  • 143
  • 1
  • 1
  • 9

1 Answers1

6

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");
};
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • 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? – NotUser9123 Sep 14 '19 at 13:27
  • 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) – Jaromanda X Sep 14 '19 at 13:28
  • 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`? – NotUser9123 Sep 15 '19 at 11:32
  • 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 – Jaromanda X Sep 15 '19 at 11:38
  • If we wait for onload outside of window (eg. in iframe) - that method doesn't work – dy_ Aug 23 '22 at 19:20
  • @dy_ I forgot, iframes don't have `window` - thank god you're here to correct my code – Jaromanda X Aug 23 '22 at 22:34