background preloader

Web Workers

Facebook Twitter

9 Web workers. 10 Web workers 10.1 Introduction 10.1.1 Scope This section is non-normative. This specification defines an API for running scripts in the background independently of any user interface scripts. This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive. Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost. 10.1.2 Examples There are a variety of uses that workers can be put to. 10.1.2.1 A background number-crunching worker The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.

<! <! <! <! Web Workers en HTML5. Paseo Aleatorio « 4lberto's Blog. Ver Demo Una de las novedades de HTML5 es la posibilidad de crear hilos de ejecución para ejecutar tareas en segundo plano con el fin de no entorpecer la interacción del usario con la página. De este modo acciones que requieran un gran tiempo de procesamiento, especialmente en dispositivos con poca capacidad de proceso, y que bloquean la interface (más de 250ms), pueden ser ejecutadas en segundo plano.

Estos hilos han sido denominados Web Workers, y como todo lo de HTML5, se programan usando Javascript. De momento sólo funcionan en las versiones más actuales de Firefox y Google Chrome. Para usar un WebWorker simplemente hay que instanciarlo en el código JavaScript: Como se puede ver, recibe por parámetro un fichero de Javascript, que contiene el código que se va a ejecutar cuando se lance el hilo.

Dentro del código del hilo (hilo1.js) está lo necesario para responder a esta llamada, devolviendo otro mensaje. documentparentwindowotras librerías como jQuery o Prototype Vamos por partes. HTML5 Web Workers: aplicación práctica con Canvas. Soporte , y Configurar parámetros para generar Fractal Ejemplo 1: Fractal con Ejemplo 2: Fractal con y Ejemplo 3: Fractal con y un con Ejemplo 4: Fractal con y tres con Ejemplo 5: Fractal con , , y Ejemplo 6: Fractal con , , , y Ejemplo 7: Fractal con , , , y , gestionado en secciones Resumen de ejecución con en navegadores En html5test.com se puede comprobar el soporte de las características de HTML5 en los navegadores, observándose que los actuales soportan los , aunque con distinto grado en la adopción de las particularidades de esta característica.

Dado el diferente nivel de soporte de los navegadores con los Workers, es necesario detectarlo previamente y actuar en su caso. Test de soporte worker y prueba de envío y transferencia de un arrayBuffer usando el módulo con la función testWorker() : Soporte worker : true Soporte arrayBuffer : false Soporte Uint8Array : false Soporte Uint8ClampedArray : false Soporte testArray : true Soporte testBuffer : false Soporte testTransferable : false. Web Workers in IE10: Background JavaScript Makes Web Apps Faster - IEBlog. Responsive Web pages result in happier consumers. With Web workers, Web applications are more responsive by offloading complex JavaScript algorithms to run in the background.

For example, in this test drive (link), you can see that offloading the work to calculate movement of water in the fountains via Web workers makes the main page more responsive for consumers: This video shows Web Workers in action in the second IE10 Platform Preview. For a closer look at the code behind this demo, watch this video. This example (link) shows the difference in how Web workers help run the ECMAScript test suite much faster. With Web workers, the script on the page runs in parallel without the interruptions of page updates. The difference in elapsed time between today’s programming model and what is possible using Web workers will help the Web get faster.

IE10 Platform Preview 2 includes complete tooling support for Web workers. New Web App Scenarios with Background JavaScript if (window.Worker) { Ie.microsoft.com/testdrive/Graphics/WorkerFountains/Default.html. A set of animated water fountains are rendered by a Web Worker and composited together into an HTML5 Canvas element. The background image is the Bellagio Casino in Las Vegas W3C Web Workers are containers for running JavaScript independently of the code on a web page. Web workers keep a web page responsive by offloading long-running JavaScript to the background.

In this demo, web workers offload the task of generating frames for the fountain animations, which improves the page's overall frame rate (versus not using web workers). Enjoy the show, or use the controls at the bottom to experiement with the fountains. BUFFER SIZE: ... frames GENERATOR RATE: 559.2140476190476 points/millisecond Web Worker Fountains are generating animation frames composed of particles (each water droplet) and sending them to the web page via postMessage() where they are composited onto a canvas.

The overall frame rate of this demo depends on the performance of several subsystems: Demos Web Workers. The Basics of Web Workers. The Problem: JavaScript Concurrency There are a number of bottlenecks preventing interesting applications from being ported (say, from server-heavy implementations) to client-side JavaScript. Some of these include browser compatibility, static typing, accessibility, and performance. Fortunately, the latter is quickly becoming a thing of the past as browser vendors rapidly improve the speed of their JavaScript engines. One thing that's remained a hindrance for JavaScript is actually the language itself. JavaScript is a single-threaded environment, meaning multiple scripts cannot run at the same time.

As an example, imagine a site that needs to handle UI events, query and process large amounts of API data, and manipulate the DOM. Pretty common, right? Developers mimic 'concurrency' by using techniques like setTimeout(), setInterval(), XMLHttpRequest, and event handlers. Introducing Web Workers: Bring Threading to JavaScript Types of Web Workers Getting Started Main script: doWork2.js: Blob URLs.

HTML5 Web Workers: la concurrencia en JavaScript. Actualización Noviembre 2012: He actualizado este tema agregando código resaltado y revisando algunas cosas. Concurrencia en JavaScript con Web Workers La especificación WHATWG Web Workers define una API para ejecutar JavaScript en segundo plano de forma independiente a la ejecución de la interfaz de usuario. Lenguajes de elevadas prestaciones como Java tienen características creadas para usar hilos de ejecución. Se trata de realizar tareas de forma concurrente.

JavaScript no posee la característica de la concurrencia y los Web Workers intentan llenar este hueco. Hay dos tipos de Workers, dedicados y compartidos. Antes de seguir veámos como usar un Worker. El código de este ejemplo es: Cómo resaltar Código El navegador implementará en su caso Worker como un objeto Function. El botón Llamar al Worker1 ejecuta el código worker1.postMessage(...) enviando el valor contenido en el cuadro de texto al Worker. Los manejadores de eventos están especificados en W3C eventTarget. Ejemplo: Número: HTML5 Web Workers.