0
How to check if the script is being called from a (Web|Service) Worker?
I have been using UMD for a long time and am migrating my projects to support SW ... although I use many features available only on objects window
and document
many features (utilities) I wish to share in SW (import) but I have to "duplicate" these resources separating them into new files to actually import (importScripts()
) because it’s the same thing I do when using Web Workers.
I started to look at it in a more "critical" way and ask myself:
How to identify in which context the code is being executed?
Based on this "context" move to export only one set of utilities... for now what I have based on this:
;((root, factory) => {
// UMD (Universal Module Definition) [improved]
if ( typeof define === 'function' && define.amd ) {
define(['exports'], factory)
} else if ( typeof exports !== 'undefined' ) {
factory(exports)
} else {
factory(root)
}
})(this, exports => {
let A, B, C
const A = 'a'
const B = 'b'
const C = 'c'
function Plugin(){}
// prototype
Plugin.prototype.functionA = function(param) {}
Plugin.prototype.functionB = function(param) {}
Plugin.prototype.functionC = function(param) {}
exports.CorePlugin = new Plugin()
});
Exporting everything that is "exportable" to the object window
:
window.CorePlugin
How could something like this:
function SWPlugin() {
// um conjunto de ferramentas exclusivas para Service Worker
}
function WWPlugin() {
// exportar um conjunto de ferramentas exclusivas para Web Worker
}
function Plugin() {
// a exportação padrão para `window`
}
// verificar
if ( ISWORKER ) {
exports.CorePlugin = new WWPlugin()
} else if ( ISSERVICE ) {
exports.CorePlugin = new SWPlugin()
} else {
exports.CorePlugin = new Plugin()
}