为 webworkers 中的导入脚本指定字符集
Specify charset for importscripts in webworkers
我正在使用 webworker 独立于我的主 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 b.t.w。)
这是毫无疑问的。即使在 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 );
};
}
当然,有很多解决方法:
- 绝对最好的解决方案是 re-encode 您的脚本为 UTF-8。
- 另一个完全 hacky 的解决方案是将您的脚本作为 Blob 获取,使用正确的编码将其作为 DOMString 读取,然后生成一个新的 UTF-8 Blob,您将提供给
importScripts
。 Doable,但是真的很丑
我正在使用 webworker 独立于我的主 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 b.t.w。)
这是毫无疑问的。即使在 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 );
};
}
当然,有很多解决方法:
- 绝对最好的解决方案是 re-encode 您的脚本为 UTF-8。
- 另一个完全 hacky 的解决方案是将您的脚本作为 Blob 获取,使用正确的编码将其作为 DOMString 读取,然后生成一个新的 UTF-8 Blob,您将提供给
importScripts
。 Doable,但是真的很丑