Service worker dynamic script import

181 views
Skip to first unread message

Don Schmitt

unread,
Sep 19, 2022, 12:16:45 PM9/19/22
to chromium-extensions
Is there a way to dynamically import scripts after the service worker has started?

importScripts returns the explicit error "importScripts() of new scripts after service worker installation is not allowed."

We have some scripts that only need to be loaded if there are specific settings in the storage which can only be accessed asynchronously.  Any solution to that?

wOxxOm

unread,
Sep 20, 2022, 10:59:07 AM9/20/22
to Chromium Extensions, Don Schmitt
Yes, with a twist: until https://crbug.com/1198822 is fixed you need to call importScripts with the same scripts additionally in the oninstall event of the service worker. It will run once after installation so make sure to account for that in the imported code either by setting a global variable before importing or just make the scripts "pure" i.e. without side effects, so they only define stuff like functions or variables, which will be called by the initiator.

Here's an example copied from https://stackoverflow.com/a/66408379/

const importedScripts = [];

function tryImport(...fileNames) {
  try {
    const toRun = new Set(fileNames.filter(f => !importedScripts.includes(f)));
    if (toRun.length) {
      importedScripts.push(...toRun);
      importScripts(...toRun);
    }
    return true;
  } catch (e) {
    console.error(e);
  }
}

self.oninstall = () => {
  // The imported script shouldn't do anything, but only declare a global function
  // (someComplexScriptAsyncHandler) or use an analog of require() to register a module
  tryImport('/js/some-complex-script.js');
};

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.action === 'somethingComplex') {
    if (tryImport('/js/some-complex-script.js')) {
      // calling a global function from some-complex-script.js
      someComplexScriptAsyncHandler(msg, sender, sendResponse);
      return true;
    }
  }
});


Reply all
Reply to author
Forward
0 new messages