我正在使用 webworkers 与我的主 js 线程分开执行脚本。在webworker中导入脚本时如何指定字符集?
最佳答案
没有明确的方法来做到这一点。
根据规范,fetch a classic worker imported script 必须将获取的数据读取为 UTF-8:
- Let source text be the result of UTF-8 decoding response's body.
(同样适用于 fetch a classic worker script 顺便说一句)
这毫无疑问。即使在 Content-Type header 中设置字符集也无济于事(尽管它应该适用于 fetching classic scripts )。
现在,Chrome 似乎不遵守此规则(至少对于 data://URL 而言,我没有尝试提供真实的文件,对于 blob://URL,他们甚至不查看定义的字符集...),但 Firefox 确实如此。
// we store the text encoded as base64 to preserve the encoding
// original text is `postMessage("é and ü")`
const script_url = "data:text/javascript;charset=windows-1252;base64,cG9zdE1lc3NhZ2UoIukgYW5kIPwiKQ==";
// importScript() test
{
const worker_script = `importScripts( "${ script_url }" );`;
const import_worker = new Worker( URL.createObjectURL( new Blob( [ worker_script ], { type: "text/javascript" } ) ) );
import_worker.onmessage = (evt) => {
console.log( 'importScripts:', evt.data );
};
}
// Worker script test
{
const direct_worker = new Worker( script_url );
direct_worker.onmessage = (evt) => {
console.log( 'worker script:', evt.data );
};
}
// inline script test
{
const script = document.createElement( 'script' );
script.src = script_url;
document.head.append( script );
onmessage = (evt) => {
console.log( 'inline-script:', evt.data );
};
}
当然,有一些方法可以解决这个问题:
- 绝对最好的解决方案是将脚本重新编码为 UTF-8。
- 另一个完全 hacky 的解决方案是将脚本作为 Blob 获取,使用正确的编码将其作为 DOMString 读取,然后生成一个新的 UTF-8 Blob,将其提供给
importScripts
。 Doable ,但是真的很丑。
关于javascript - 为 webworkers 中的导入脚本指定字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61122164/