Search code examples
javascriptweb-worker

ImportScripts() web worker scope of variables


Does this code

if (typeof importScripts === 'function') {

importScripts('somelib.js');

}

//some code between

if (typeof importScripts === 'function') {
    var i = some_function_from_imported_lib(params);
//CODE CODE CODE
}

is the same as

if (typeof importScripts === 'function') {

importScripts('somelib.js');
    var i = some_function_from_imported_lib(params);
//CODE CODE CODE
}

?

In other words, does it matter importScripts() is wrapped by some parenthesises or not? Does it matter for scope of functions and variables inside somelib.js?


Solution

  • That completely depends on:

    //some code between
    

    If that "some" code doesn't have any effect on the imported lib's functions, or your parameters, then:

    if (typeof importScripts === 'function') {
        importScripts('somelib.js');
    }
    //some code between
    if (typeof importScripts === 'function') {
        var i = some_function_from_imported_lib(params);
    }
    

    Is functionally the same as:

    if (typeof importScripts === 'function') {
        importScripts('somelib.js');
        var i = some_function_from_imported_lib(params);
    }
    

    Those if blocks don't have their own scope.