1. Web Worker

为Web内容在后台线程中运行脚本提供了一种简单的方法。线程可以执行任务而不干扰用户界面

1.1. 简单理解

  • 主线程 worker.postMessage -> 子线程 self.onmessage func --//-- self.postMessage -> 主线程 worker.onmessage func
  • 子线程无法操作dom 通过通信方式 完成操作页面
  • 下述例子 使用centrifuge websocket 通过子线程 通知主线程 操作页面

1.2. 子线程执行 t.js

importScripts('./centrifuge.js');
importScripts('./sockjs.js');
var centrifuge  = new Centrifuge('http://test.yogurt.top:8000/connection/sockjs',{
    sockjs:SockJS,
    sockjsTransports:[
        "websocket",
        "xhr-streaming",
        'websocket',
        'xdr-streaming',
        'xhr-streaming',
        'eventsource',
        'iframe-eventsource',
        'iframe-htmlfile',
        'xdr-polling',
        'xhr-polling',
        'iframe-xhr-polling',
        'jsonp-polling'
    ]
});

centrifuge.setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIifQ.u3AUlu9-T1fGuV7i5N-X_ZLrhJj3-vDsWHl_hcNapYY');
var subscription = centrifuge.subscribe("public:brief", function(response) {
    console.log(response);
    postMessage(response);
})
centrifuge.on('connect', function(context) {
    // now client connected to Centrifugo and authorized
    console.log("connect==>",context)
});
subscription.history().then(function(message) {
    // history messages received
    console.log('history==>',message)

}, function(err) {
    // history call failed with error
});
centrifuge.connect();
onmessage = function(e) {
    console.log('t.js===<<>>' , e)
    postMessage(e.data);
}

1.3. 主线程 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>--</title>
</head>
<body>
<p id="main"> 1 </p>
<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
<script type="text/javascript">
    if (window.Worker) {
        const worker = new Worker("./t.js");
        worker.onmessage = function(e) {
            console.log('Message received from worker',e.data);
            $("#main").text(e.data.data.message.article_title);
        }
        worker.onerror = function (e) {
            console.log([
                'ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message
            ].join(''));
        }
//        worker.terminate();
    } else {
        console.log('Your browser doesn\'t support web workers.')
    }
</script>
</body>
</html>

results matching ""

    No results matching ""