Get the App
SLTechnology News&Howtos  ›  Development  › 

How to detect whether the browser supports WebWorker

Shulou Source: shulou.com Published: 2022-06-01 04:08:47 09月13日 Update

This article introduces the knowledge of "how to detect whether the browser supports WebWorker". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Check whether the browser supports WebWorker

Before you create a webworker, check if the user's browser supports it:

If (typeof (Worker)! = "undefined")

{

/ / Yes! Web worker support!

/ / some code.

}

Else

{

/ / Sorry! Web Worker does not support

}

Create a webworker file

Now, let's create our webworker in an external JavaScript.

Here, we create a count script. The script is stored in the "demo_workers.js" file:

Var iTunes 0

Function timedCount ()

{

I=i+1

PostMessage (I)

SetTimeout ("timedCount ()")

}

TimedCount ()

The important part of the above code is the postMessage () method, which is used to return a message to the HTML page.

Note: webworker is not usually used for such simple scripts, but for tasks that consume more CPU resources.

Create a WebWorker object

We already have the webworker file, and now we need to call it from the HTML page.

The following code detects whether worker exists, and if not,-it creates a new webworker object and then runs the code in "demo_workers.js":

If (typeof (w) = = "undefined")

{

W=new Worker ("demo_workers.js")

}

Then we can generate and receive messages from webworker.

Add a "onmessage" event listener to webworker:

W.onmessage=function (event) {

Document.getElementById ("result") [xss_clean] = event.data

}

Terminating WebWorker

When we create the webworker object, it continues to listen to the message (even after the external script completes) until it is terminated.

To terminate webworker and release browser / computer resources, use the terminate () method:

W.terminate ()

WebWorkers and DOM

Because webworker is in an external file, they cannot access the following JavaScript objects:

Window object

Document object

Parent object

This is the end of the content of "how to detect whether the browser supports WebWorker". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Objects support browsing detection browsing code files scripts messages content methods more knowledge resources pages monitoring practical important sorry learned Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Information Linux Microsoft Redmi