worker.js: window is not defined

Advertisements

I am trying to make a worker that will run automatically and constantly check the browser’s width, but, I am getting this error: worker.js:1 Uncaught ReferenceError: window is not defined at worker.js:1:18

This is the code:

var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
    var nav = document.getElementById("navigation-bar");

    if (window.screen.width >= 1200) {
        console.log(window.screen.width, 'Stay In desktop version');
    }
    else {
        console.log(window.screen.width, 'Switch to mobile version');
    }
}

I saw this issue and had questions about it. Although This issue for some people was solved, their solutions are not helpful in my case.

>Solution :

See MDN:

Not all interfaces and functions are available to scripts inside a Worker

And the linked document:

Workers run in a different global context than the current window! While Window is not directly available to workers, many of the same methods are defined in a shared mixin (WindowOrWorkerGlobalScope), and made available to workers through their own WorkerGlobalScope-derived contexts


So you can’t access window but you can get access to setInterval just by reading it as a global instead of from the non-existent window.

Then you run into the document and screen not being available.


There is no point in using a Worker what you are trying to do.

Workers are for running CPU-intensive code outside the main event loop so it doesn’t block the rest of the page.

Any interaction with the DOM or main window needs to be done inside the main event loop. Messages can be used to pass data between a worker (doing expensive calculations) and the main event loop (which has access to the window and DOM).

You aren’t doing anything CPU intensive, so you don’t need to use a worker at all.


Aside: Polling the size of the window is inefficient too. You can listen for an event if you want to know when the window size changes and even that is probably isn’t needed given the existence of CSS media queries.

Leave a ReplyCancel reply