Combining Library and Worker code in one script.

Worker location is determined relative to the html page not to the script that calls them. So if you need to call a worker from a script that might be called as <script src="script.js"> on one page and <script src="js/script.js"> on another this pattern lets you avoid using absolute URLs.

 if (typeof document === "undefined") {(function(self){
                /*
                worker stuff
                */
})(self)} else {(function(exports){
        "use strict";
        function getPath(){
                var scripts = document.getElementsByTagName("script");
                var len = scripts.length;
                var i = 0;
                while(i<len){
/*  change  --------> */if(/scriptWithWorker(\.min)?\.js/.test(scripts[i].src)){
                                return scripts[i].src;
                        }
                        i++;
                }
        }
        var worker = new Worker(getPath());
        /*
        non-worker code
        */
})(window)};

Author: Calvin Metcalf
Tags: workers

comments powered by Disqus