Статьи

Веб-работники в HTML5

Эти требования приложений звучат знакомо?

  • Использование фоновых операций ввода-вывода
  • Опрос веб-сервисов
  • Обработка большого количества данных
  • Запуск алгоритма в фоновом режиме
  • Больше

Если вы работаете в среде Windows, вы, вероятно, будете использовать фоновый рабочий (или другой поток) для выполнения этих требований, чтобы сделать ваше приложение более отзывчивым. В веб-среде это было невозможно, поскольку JavaScript является однопоточным окружением. Вы не можете запускать несколько сценариев одновременно, но вы можете совершать хаки, используя такие функции, как setInterval. В HTML5 в настоящее время разрабатывается новый API, чтобы веб-приложения могли запускать фоновые сценарии. В этой статье я собираюсь объяснить этот API — Web Workers — и показать вам, как вы можете использовать их сегодня с большинством основных браузеров (не включая IE9).  

Что такое веб-работники?

API Web Workers находится в стадии разработки. Веб-работники — это фоновые работники, которые запускают сценарии параллельно своей главной странице. Сам Web Worker не зависит от сценариев пользовательского интерфейса. Они позволяют выполнять нитевидные операции на стороне клиента, которые включают механизм передачи сообщений для координации или извлечения данных. Если вы ожидали, что процесс будет долгоживущим, с высокой стоимостью запуска и высокой стоимостью памяти для каждого экземпляра, Web Workers могут быть хорошим решением.

Как использовать API Web Workers?

Спецификация для веб-работников определяет два типа работников — выделенные работники и общие работники. Первый вид оборачивает задание и выполняет его. Второй может иметь несколько соединений и использует порты для отправки сообщений.

Первое, что нужно сделать, чтобы использовать API Web Workers, — создать работника и передать ему URL сценария выполнения. Вот пример того, как сделать это с выделенными работниками:

var worker = new Worker('worker.js');

В Shared Web Workers вы создадите объект SharedWorker вместо объекта Worker: 

var worker = new SharedWorker('worker.js');

При создании веб-работника он предоставляет следующие события, которые помогают главной странице взаимодействовать с работником:

  • onerror — сигнализирует о том, что в работнике произошла ошибка
  • onmessage — позволяет получать рабочие сообщения обратно на главную страницу. Эти сообщения вызываются внутренним рабочим событием postMessage

Также работник выставляет следующие внутренние функции:

  • прекратить — остановить выполнение работника
  • postMessage — отправляет сообщение для слушателей события onmessage на главной странице

In Shared Web Workers you have an addition inner event – onconnect and also the port object. I won’t discuss Shared Web Workers so you can read about them in the Web Workers current draft. After we understand a little bit about  What are Web Workers and their API lets look at an example.

Web Workers Example

The following example shows how to create a Web Worker and run it in order to call a simple Echo web service.
The service echo the data it receives and its implementation looks like:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]  
[ScriptService]
public class EchoService : WebService
{
  [WebMethod]
  public string Echo(string msg)
  {
    return msg;
  }
}

The only interesting thing here is the ScriptService attribute that enables client scripts to call the service.
Next lets look at the worker.js file: 

var xhr;

function getData(url, params) {
    try {
        xhr = new XMLHttpRequest();        
        xhr.open('POST', url, false);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    postMessage(xhr.responseText);
                }
            }
        };
        xhr.send(params);
    } catch (e) {
        postMessage('Error occured');
    }
}
 
function callWSMethod() {
    getData("http://localhost:30051/WebWorkers/EchoService.asmx/Echo?msg=Hello", "msg=Hello");
}
 
callWSMethod();

In the worker’s script there are two functions. The first function (getData) is used to make the request to the service and to post messages back to the main page when the data returns from the service. The second function (callWSMethod) just call the first function with some test data.

The last piece of code is the main page itself:

<!DOCTYPE HTML>
<html>
<head>
    <title>Worker example: Simple Ajax Call</title>
</head>
<body>
    <p>
        Result:
        <output id="result">
        </output></p>
    <script type="text/javascript">       
        var worker = new Worker('worker.js');
        worker.onmessage = function (event) {            
            document.getElementById('result').innerHTML = event.data;
        };
    </script>
</body>
</html>

As you can see the Web Worker is being created by using the worker.js file and a handler is wire to the onmessage event. The handler inserts the data returned by the postMessage function (that exists inside the worker.js) into an output element (a new HTML5 element for outputs). You can try this example on Chrome and then you’ll get the following result:

WebWorkerResult

This is a very simple example and you can start thinking how to take this API to the next level in order to do more interesting things.

Summary

Lets sum up, Web Workers API enables the creation of background scripts which can communicate with the main page. This ability is very powerful and can help web developers to create more responsive UI and to achieve things that couldn’t be achieved in web applications in the past. Currently Web Workers are only a draft but there are browsers that support them currently such as Chrome, FireFox and Opera. For further details about Web Workers you can read the Web Workers current draft.

 

Source: http://blogs.microsoft.co.il/blogs/gilf/archive/2011/04/08/web-workers-in-html5.aspx