javascriptweb-worker

Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope'


I am trying to import json data from web worker using importScripts, the following error occurs.

Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at (my:URL to fetch data from server) failed to load.

Web worker code is here. I am able to send basic messages from my web worker thread and main js thread. I want to fetch jsonp data from my server from web worker thread and then reply to main js thread.

/*web worker js file to fetch json data from server and then return to main javascript thread*/

self.onmessage = function(e)
{
    var curr = setInterval(function()
    {
    
         var message = e.data;     
            fetchMyTournament(message);
    
    }, 10000);
}



function fetchMyTournament(userid)
{
    self.postMessage('worker saying hi');
       
    
    var url = "(server URL mapping)?callback=processInfo&type=(typeOfArgument)&userId="+userid;
    
               
               
               importScripts(url);
            self.postMessage("After import script");

            
       
}
function processInfo(objJSON) 
{
 
    self.postMessage("Data returned from the server...: " 
                  + JSON.stringify(objJSON));
} 

Solution

  • importScript() must be placed outside of a function. For your case you should use fetch(url). You should also add async to each function, and use it this way:

    let message = fetchMyTournament(message).then(function(result){return result;});