Search code examples
javascriptimportweb-worker

importScripts in webworker, ignore reference exceptions


I am trying to import a javascript file in a webworker which contains document references and therefore fails. Is it possible to supress the reference exceptions? I only need a handfull of functions from the javascript file which should not use the document object. Or do I need to rebuild the js library from source excluding everything I won't need.

Cheers, Dennis


Solution

  • I did something similar to load Angular in a web worker, in https://stackoverflow.com/a/27931746/1319998 . My solution was to create dummy versions of the objects in the global scope, with just enough properties and functions so Angular wouldn't throw exceptions when it tried to access them, and then load Angular using importScripts.

    The code below is what worked for me for Angular, which needed not only document , but window and history as well

    // In the web worker
    
    // Angular needs a global window object
    self.window = self;
    
    // Skeleton properties to get Angular to load and bootstrap.
    self.history = {};
    self.document = {
      readyState: 'complete',
      querySelector: function() {},
      createElement: function() {
        return {
          pathname: '',
          setAttribute: function() {}
        }
      }
    };
    
    // Load Angular: must be on same domain as this script
    self.importScripts('angular.js');