newbie newbie -4 years ago 115
jQuery Question

executing jquery function after a global object resolved

In my page I have following scripts that will be loaded:

<script src="~/js/dir/search.js"></script>
<script src="~/js/dir/item.js"></script>


Inside
search.js
file I use ES6 inside global scope:

fetch(endpoint)
.then(blob => blob.json())
.then(data => members.push(...data));


And inside
item.js
I use this script to show
members
object:

$(window).load(() => {
console.log(members);
});


But it prints
undefined
in the console, How do I ensure that if
search.js
completely loads then
items.js
give the result?

Answer Source

You could expose an API from one file to register an extra handler in the other.

search.js:

var p = fetch(endpoint);
p.then(…);
window.extraHandler = function (fn){
    p.then(fn);
}

item.js:

extraHandler(function(){
    console.log(members);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download