Web Worker 中的 RequireJS [英] RequireJS in web worker

查看:21
本文介绍了Web Worker 中的 RequireJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Web Worker 中使用 RequireJS.问题是我在使用它时不断收到以下错误.未捕获的错误:./lib/underscore.js 处的下划线导入脚本失败

I am trying to use RequireJS inside a web worker. The problem is that I keep getting the following error when using it. Uncaught Error: importScripts failed for underscore at ./lib/underscore.js

我已经测试了我的配置选项,它们只会在导入 Underscore 时导致此错误.他们在这里:

I have tested my configuration options, and they only cause this error when importing Underscore. Here they are:

{
    baseUrl: './',
    paths: {
        jquery: 'lib/jquery',
        underscore: 'lib/underscore'
    },
    shim: {
        underscore: {
            exports: '_'
        }
    }
}

如有必要,我可以添加更多信息.此项目的源代码位于 GitHub 上,地址为 https://github.com/isaach1000/canvas.

I can add more info if necessary. The source for this project is on GitHub at https://github.com/isaach1000/canvas.

更新: 修复 RequireJS 仍然没有运气,但我使用 Grunt 任务修复了我的问题.这是配置:

UPDATE: Still no luck on fixing RequireJS, but I fixed my issue using a Grunt task. Here is the configuration:

requirejs: {
    worker: {
            options: {
                baseUrl: 'js',
                name: 'task',
                out: 'build/task.js',
                paths: {
                    jquery: 'lib/jquery',
                    underscore: 'lib/underscore'
                },
                shim: {
                    underscore: {
                        exports: '_'
                    }
                },
                include: ['lib/require.js'],
                optimize: 'none'
            }
     }
}

推荐答案

您是否使用 importScriptsrequire 正确加载到 Worker 中?

Did you load require properly into the Worker by using importScripts?

importScripts('path/to/require.js');

require({ ... });

require repo 中的测试很好的例子,另请参阅 How to使用 Requirejs 将 Web Workers 用于模块构建?

The test in the require repo is a pretty good example, also see Chad's answer in How to use Web Workers into a Module build with Requirejs?

网络工作者有一个专用的全球范围.问题很可能是因为 Underscore 直到 1.6.0 版才使用 AMD(2014 年 2 月,在您发布之后问题).

Web workers have a dedicated global scope. The problem was most likely exacerbated by Underscore not using AMD until version 1.6.0 (February 2014, after you posted the question).

我强烈建议使用 importScripts()(MDN),正如本杰明对您的原始问题的评论所建议的.

I would highly recommend using importScripts() (MDN) as suggested by Benjamin's comment on your original question.

标准定义可以在 https 中找到://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries

确保 require 在不同平台上适用于 webWorkers 中的所有库的麻烦不值得这种便利,而且性能方面不会受到任何影响因为工作人员不会影响主应用的性能.

The hassle you get for making sure require works for all libs in webWorkers across different platforms is not worth the convenience, and performance wise it doesn't take any hit as workers don't affect the performance of your main app.

这篇关于Web Worker 中的 RequireJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆