Skip to content Skip to sidebar Skip to footer

How To Pass An Object Name To A JavaScript Promise That Waits Until The Object Has Been Initiated?

I need a function that resolves a JavaScript promise as soon as an object is defined. I'm a WordPress plugin developer and I face the problem that I have no control over where my c

Solution 1:

If the object will be global, pass a string and use typeof instead, which will work for variables that haven't been defined yet:

function objectExists(varName) {
    return new Promise(function (resolve, reject) {
        (function waitForObject() {
            if (typeof window[varName] !== 'undefined') return resolve();
            setTimeout(waitForObject, 30);
        })();
    });
}


objectExists('jQuery').then(function () {
  // run my code
});

(or you could use your existing code with window.jQuery instead - referencing a non-existent property of an object won't throw an error)

But this is a really weird thing to want to do. Better to attach a load listener to the jQuery <script> tag.


Post a Comment for "How To Pass An Object Name To A JavaScript Promise That Waits Until The Object Has Been Initiated?"