6. 应用程序缓存
1 var i=0;
2
3 function timedCount()
4 {
5 i=i+1;
6 postMessage(i);
7 setTimeout("timedCount()",500);
8 }
9
10 timedCount();
1 <!DOCTYPE html>
2 <html>
3 <body>
4
5 <p>Count numbers: <output id="result"></output></p>
6 <button onclick="startWorker()">Start Worker</button>
7 <button onclick="stopWorker()">Stop Worker</button>
8 <br /><br />
9
10 <script>
11 var w;
12
13 function startWorker()
14 {
15 if(typeof(Worker)!=="undefined")
16 {
17 if(typeof(w)=="undefined")
18 {
19 w=new Worker("demo_workers.js");
20 }
21 w.onmessage = function (event) {
22 document.getElementById("result").innerHTML=event.data;
23 };
24 }
25 else
26 {
27 document.getElementById("result").innerHTML="Sorry, your browser
28 does not support Web Workers...";
29 }
30 }
31
32 function stopWorker()
33 {
34 w.terminate();
35 }
36 </script>
37
38 </body>
39 </html>
1 <!DOCTYPE html>
2 <html>
3 <body>
4 <h1>获得服务器更新</h1>
5 <div id="result"></div>
6
7 <script>
8 if(typeof(EventSource)!=="undefined")
9 {
10 var source=new EventSource("/example/html5/demo_sse.php");
11 source.onmessage=function(event)
12 {
13 document.getElementById("result").innerHTML+=event.data + "<br />";
14 };
15 }
16 else
17 {
18 document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
19 }
20 </script>
21
22 </body>
23 </html>
需要能够发送数据更新的服务器(比如 PHP 和 ASP)。
服务器端事件流的语法是非常简单的。把 "Content-Type" 报头设置为 "text/event-stream"。现在,您可以开始发送事件流了。
1 <?php
2 header(‘Content-Type: text/event-stream‘);
3 header(‘Cache-Control: no-cache‘);
4
5 $time = date(‘r‘);
6 echo "data: The server time is: {$time}\n\n";
7 flush();
8 ?>