Reputation: 143
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?
Upvotes: 1
Views: 15098
Reputation: 1
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");
};
Upvotes: 10