How to check if the script is being called from a (Web | Service) Worker?
I have used UMD for a long time and I am migrating my projects to support SW ... although, I use many features available only on window
objects and document
many features (utilities) I want to share in SW (import) more I just have to "duplicate" these resources by 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 this in a more "critical" way and ask myself:
How to identify in what context the code is running?
Based on this "context" export only a set of utilities ... per hour what I have is 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()
}