javascript 未捕获的网络错误:无法在“WorkerGlobalScope”上执行“importScripts”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24349175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:36:45  来源:igfitidea点击:

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

javascriptweb-worker

提问by user3462649

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

我正在尝试使用 importSctipts 从 web worker 导入 json 数据,出现以下错误。

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

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 线程发送基本消息。我想从 Web 工作线程从我的服务器获取 jsonp 数据,然后回复主 js 线程。

/*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));
} 

回答by mazout

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:

importScript() 必须放在函数之外。对于您的情况,您应该使用 fetch(url)。您还应该为每个函数添加异步,并以这种方式使用它:

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

回答by nawaz1989

For my case i was importing PouchDB like this: importScripts("//cdn.jsdelivr.net/pouchdb/5.3.1/pouchdb.min.js");

就我而言,我是这样导入 PouchDB 的: importScripts("//cdn.jsdelivr.net/pouchdb/5.3.1/pouchdb.min.js");

The url should start with proper http/https. So changing to this solved the problem: importScripts("https://cdn.jsdelivr.net/pouchdb/5.3.1/pouchdb.min.js");

url 应该以正确的 http/https 开头。所以改成这个就解决了这个问题: importScripts("https://cdn.jsdelivr.net/pouchdb/5.3.1/pouchdb.min.js");