First of all, we need to understand what webworker is, which is generally understood as multi-threading on the Web side. Do anything inside without blocking the thread, but you can’t perform DOM operations inside.
This is premise, had very early, detail can see this ruan yifeng this this article
www.ruanyifeng.com/blog/2018/0…
Application in Webpack
deep-thought.js
self.onmessage = ({ data: { question } }) => {
self.postMessage({
answer: 42,
});
};
Copy the code
index.js
const worker = new Worker(new URL('./deep-thought.js', import.meta.url));
worker.postMessage({
question:
'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
});
worker.onmessage = ({ data: { answer } }) => {
console.log(answer);
};
Copy the code
So these two become answer is equal to 42
Webworkers cannot be debugged locally, so just run a service to debug them
2 parameters
Generally, we use Webworker in the following way
new Worker("http....." )Copy the code
There is a direct address, you can also write it in webpack, but that’s not convenient
If you refer directly to the address in /dist, you need to change it every time, and you need to configure the prefix.
I thought it was the URL that concatenated the address
new Worker(new URL('./deep-thought.js', import.meta.url));
Copy the code
Adding import.meta.url to automatically draw conclusions based on browser information, I realized I was overthinking it
const o = new Worker(new URL(r.p + r.u(415), r.b))
r.b = document.baseURI || self.location.href
r.p = e
e = r.g.location + ""
r.g = function () {
if ("object" == typeof globalThis)
return globalThis;
try {
return this || new Function("return this")()
} catch (e) {
if ("object" == typeof window) return window
}
}()
Copy the code
You can see it here.
In fact, it is mainly webpack parsing, whether the USE of URL is not too important.
2.1 the URL
new URL("https://www.baidu.com") URL {origin: "https://www.baidu.com", protocol: "https:", username: "", password: "Host:", "www.baidu.com",... } hash: "" host: "www.baidu.com" hostname: "www.baidu.com" href: "https://www.baidu.com/" origin: "https://www.baidu.com" password: "" pathname: "/" port: "" protocol: "https:" search: "" searchParams: URLSearchParams {} username: ""Copy the code
The return parameter is similar to window.location, but it can return information from other web pages
See the API here
Developer.mozilla.org/zh-CN/docs/…
Developer.mozilla.org/zh-CN/docs/…
caniuse.com/?search=URL
2.2 the import. Meta
Although this code is referenced here, it is only for webPack generation
For practical purposes, see here
Developer.mozilla.org/zh-CN/docs/…
Caniuse.com/?search=imp…
end
www.ruanyifeng.com/blog/2018/0…
Blog.csdn.net/weixin_4282…