Polarize
Polarize

Reputation: 1035

Using a variable to search for property in window using 'in'

I am trying to loop through an array of required names of properties that should be in the Window before the script will continue. However, JavaScript doesn't seem to like it when I use a variable instead of explicit text when using the 'in' keyword.

TypeError: Cannot use 'in' operator to search for 'ServiceWorker' in window

Am I doing something wrong or is this just the way this works?

const waitForScripts = () => {
  return new Promise(function(resolve, reject) {
    var required = ["ServiceWorker"];
    var loaded = 0;

    while (loaded <= required.length + 1) {
      if (loaded == required.length) {
        resolve();
      }
      for (var i = 0; i < required.length; i++) {
        var search = required[i];
        if (search in 'window') {
          loaded++;
        }
      }
    }
  });
};

Upvotes: 0

Views: 34

Answers (2)

Gary S.
Gary S.

Reputation: 146

Gotta be careful with that while loop. If for some reason one of the property names is not on the window object, you will end up with an infinite loop because loaded will not increment.

Upvotes: 1

axelduch
axelduch

Reputation: 10849

You used the in operator on a string, you want to use it on the variable window

if (search in window) {
    loaded++;
}

Upvotes: 4

Related Questions