- webNotification
- webWorker
- webServerSentEvent
01 webnotification
使用場景
私信谈火、在線提問糯耍、或者一些在線即時通訊工具,需要知道對方有了新的反饋
獲得用戶許可
Notification.requestPermission()
查看用戶當(dāng)前許可狀態(tài)
Notification.permission
- 默認(rèn):default
- 授權(quán):granted
- 拒絕:denied
調(diào)用方式兩種回調(diào)
和鏈?zhǔn)秸{(diào)用
Notification.requestPermission().then(function(permission) { ... });
Notification.requestPermission(callback);
demo
function getPermission(fn){
Notification.requestPermission().then(function(result) {
//result可能是是granted, denied, 或default.
});
}
function notification(){
if( Notification.permission === 'granted' ){
var notification = new Notification("title", {
body: 'msg body',
icon: 'mm1.jpg'
});
notification.onclick = function(){
// ... 這里執(zhí)行跳轉(zhuǎn)
notification.close();
}
}
}
02 webWorker
使用場景
當(dāng)在 HTML 頁面中執(zhí)行腳本時,頁面的狀態(tài)是不可響應(yīng)的荒揣,直到腳本已完成焊刹。
web worker 是運行在后臺的 JavaScript虐块,獨立于其他腳本贺奠,不會影響頁面的性能。您可以繼續(xù)做任何愿意做的事情:點擊挂据、選取內(nèi)容等等崎逃,而此時 web worker 在后臺運行个绍。
webWorker 適合于消耗CPU的任務(wù)
檢測 webWorker 支持
if(typeof webWorker !== 'undefined'){
}
創(chuàng)建 webWorker 文件
var i=0;
function timedCount() {
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
重要的部分是 postMessage() 方法 - 它用于向 HTML 頁面?zhèn)骰匾欢蜗?/p>
創(chuàng)建 webWorker 對象
w=new Worker("demo_workers.js");
w.onmessage=function(event){
//event.data中有數(shù)據(jù)
document.getElementById("result").innerHTML=event.data;
};
終止 webWorker
w.terminate();
03 webServerSentEvent
使用場景
EventSource 對象用于接收服務(wù)器發(fā)送事件通知巴柿,eg微博篮洁、twitter新消息
監(jiān)聽源
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
客戶端事件
- onopen 當(dāng)通往服務(wù)器的連接被打開
- onmessage 當(dāng)接收到消息
- onerror 當(dāng)錯誤發(fā)生
demo
var source=new EventSource("demo_sse.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};