Search code examples
javascriptgoogle-chromegoogle-chrome-extensionchrome-extension-manifest-v3

Offscreen documents within or outside of Service Workers


By doing something such as opening an offscreen document for audio playback:

function offscreenCreate() 
{
   chrome.offscreen.createDocument({
       url: 'offscreen.html',
       reasons: ['AUDIO_PLAYBACK'],
       justification: "something"
   });
}

I've seen a lot of documentation and such, showcasing the operation (and other operations related to offscreen documents, such as closing them) being used within Service Workers, but are there any significant differences in putting these operations within a Service Worker Vs. outside of a Service Worker (just a regular JS file), such as performance? More specifically, is it necessary in general?


Solution

  • The purpose of an offscreen document is to do something without showing a UI page to the user, but you may want to use it even from a visible UI page such as the popup because the lifetime of an offscreen document is tied to its internal affairs and not to the environment in which it was created e.g. when playing an audio, the document lives as long as it's playing the audio and terminated after 30 seconds of silence. Currently only the audio is limited, i.e. the lifetime is unlimited otherwise, but it'll likely change in the future because ManifestV3 intentionally removes persistence as much as possible and switches to event-driven on-demand logic, hence the controversial decision to use service workers.

    There's no performance gain generally, rather there's a loss as it's a standard JS environment that consumes at least ~15MB of memory for JS engine + JS built-ins and at least 50ms of heavy CPU usage to initialize all that. However, using an offscreen document may help reduce resource usage and thus improve performance if you reduce the number of times the service worker restarts.