HTML and CSS Reference
In-Depth Information
Web workers are a great way to modularize the code in your project or creative as well. If you have UI code,
allow it to be a part of the markup, and load it independently of the worker script, which could be handling a random
number generator or something else not directly tied to the UI.
Note
Web workers need to be hosted on a local or remote server in order to operate.
Web Workers in Advertising
In advertising, web workers can enhance user experience immensely. We finally have an API for running JavaScript
in the background independent of anything else on the page, which will allow long-running tasks to be completed
without making the page unresponsive. If you're doing any sort of calculation or complex algorithms with JavaScript,
you should absolutely opt to use a web worker if they're available in the browsers you're targeting. The result is both
a better and faster experience for end users. Let's take a look at working with a simple worker that returns the user's
information from the Navigator object in their browser (see Listing 6-6).
Listing 6-6. Web Workers Ad Example (Main Script)
<!DOCTYPE HTML>
<head>
<script>
if (!!window.Worker) {
var worker = new Worker('worker.js');
// Receive the message from the worker thread
worker.onmessage = function (event) {
var workerMsg = event.data;
document.write(workerMsg);
};
} else {
console.log('No Worker Support')
}
</script>
</head>
<body>
</body>
</html>
//Code in worker.js file
for (property in navigator) {
postMessage("<b>" + property+"</b>: "+navigator[property]+"<br>");
}
From our example, you can see that, instead of setting up the worker.js script file by writing <script
src=worker.js></script> , we create a new worker object and pass it the location of the script file by writing var
worker = new Worker('worker.js'); .
Next, the worker script will run through its for loop, which will return all the properties of the user's Navigator
object through the postMessage call. Back at the main script, we handle the postMessage call by writing worker.
onmessage ; and through the event, we call a new variable, workerMsg , which we set to event.data .
 
 
Search WWH ::




Custom Search