HTML5 Web worker and SSE (Server-sent-event)

Source: Internet
Author: User

Web worker is a JavaScript that runs in the background and does not affect the performance of the page.

When you execute a script in an HTML page, the state of the page is not responsive until the script is complete.

Web Worker is a JavaScript running in the background, independent of other scripts, without affecting the performance of the page. You can continue to do anything you want to do: Click, select Content, and so on, while the Web worker runs in the background.

Create a Web worker file

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

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

var i=0;

function Timedcount ()
{
i=i+1;
PostMessage (i);
SetTimeout ("Timedcount ()", 500);
}

Timedcount ();

The important part of the above code is the PostMessage () method-it is used to return a message to an HTML page.

Note: Web workers are typically not used for such a simple script, but rather for tasks that consume more CPU resources.

To create a Web Worker object

We already have the Web worker file, and now we need to call it from the HTML page. /p>

The following code detects if a worker exists, if it does not exist-it creates a new Web Worker object, and then runs the code in "Demo_workers.js":/p>

if (typeof (W) = = "undefined")
{
W=new Worker ("Demo_workers.js");
}

Then we can take and receive messages from the Web worker.

Add a "onmessage" event listener to the Web worker:

W.onmessage=function (event) {
document.getElementById ("Result"). Innerhtml=event.data;
};

<p the code in the event listener executes when web= "worker=" "passes the message. Event.data= "" contains data from = "Event.data=" ". <= "p=" ">

Terminate Web Worker

When we create a Web worker object, it continues to listen for messages, even after the external script finishes, until it is terminated.

To terminate the Web worker and release the browser/computer resources, use the Terminate () method:

W.terminate (); Web Workers and DOM

Because web workers are located in external files, they cannot access the following JavaScript object:

    • Window object
    • Document Object
    • Parent object

HTML5 Server Send events (Server-sent event) allow Web pages to get updates from the server.

Server-sent Event-one-way message delivery

The Server-sent event refers to a webpage that automatically obtains updates from the server.

This could have been done before, provided the Web page had to ask if there were any updates available. Events are sent through the server, and updates are automatically reached.

Examples: Facebook/twitter updates, valuation updates, new posts, tournament results, and more.

Receive Server-sent event notifications

The EventSource object is used to send event notifications to the receiving server:

var source=new EventSource ("demo_sse.php"); Source.onmessage=function (event) {     document.getElementById ("Result "). Innerhtml+=event.data +" <br> ";};

Instance parsing:

    • Create a new EventSource object, and then specify the URL of the page that is sending the update ("demo_sse.php" in this case)
    • OnMessage event occurs every time an update is received
    • When the OnMessage event occurs, the received data is pushed into the element with the ID "result"
Server-side Code instances

To make the above example work, you also need a server that can send data updates (such as PHP and ASP).

The syntax of the server-side event stream is very simple. Set the "Content-type" header to "Text/event-stream". Now you can start sending the event stream.

<?php
Header (' Content-type:text/event-stream ');
Header (' Cache-control:no-cache ');

$time = Date (' R ');
echo "Data:the server time is: {$time}nn";
Flush ();
?>

ASP Code (VB) (demo_sse.asp):

<%
Response.contenttype= "Text/event-stream"
Response.expires=-1
Response.Write ("Data:" & Now ())
Response.Flush ()
%>

Code Explanation:

-Set the header "Content-type" to "Text/event-stream"

-no page caching is required

-Output Send date (always start with "data:")

-Refresh output data to Web page

EventSource Object

In the example above, we use the OnMessage event to get the message. However, you can also use other events:

Events Description
OnOpen When the connection to the server is opened
OnMessage When a message is received
OnError When an error occurs

HTML5 Web worker and SSE (Server-sent-event)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.