初识 service worker

初识 service worker

与君初相识,犹如故人归。

很早就听别人说起过 service worker, 可是直到现在才有时间来尝试这项技术。 它的理论之类的东西我就不再赘述,感兴趣自行百度,咱废话不多说先让代码飞一会(Talk is cheap, show me the code.)。

开始之前还是先了解一下基本概念:

  1. 什么是ServiceWorker?
  2. 什么是Promise?
  3. Promise例子

好了直接进入例子程序:

  • 立Flag: 在多个标签页打开此页面,在一个其中一个页面上的操作会同步到其他的页面上。
  • 目录结构:
    • worker
      • sync.html
      • task-sync.js
  • 强调一下 本例只能在 127.0.0.1(localhost) 或者 https在运行

sync.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>screen synctitle>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html, body {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            background-color: #eceff1;
        }

        .container {
            width: 80%;
            height: 80%;
            background: #fff;
        }

        .btn {
            margin: 10px;
            padding: 1em;
            background-color: aqua;
            border: 1px solid aqua;
            cursor: pointer;
            box-shadow: 5px 5px 10px #333;
            border-radius: 5px;
        }

        .btn:hover {
            background-color: olivedrab;
            border: 1px solid olivedrab;
            box-shadow: 5px 5px 5px #333;
        }

        input {
            margin: 10px;
            padding: 1em;
            border-radius: 5px;
        }

        input:hover {
            border-radius: 5px;
        }

    style>

head>
<body>

    <div class="container">
        <div class="item">
          <button class="btn" id="clickMeBtn">click mebutton>
        div>
        <div class="item">
            <input type="text" id="inputArea" placeholder="input something.">
        div>
    div>


    <script>

        (function () {
            const worker = navigator.serviceWorker;
            const btn = document.getElementById("clickMeBtn");
            const input = document.getElementById("inputArea");


            if ('serviceWorker' in navigator) {
                // 在页面加载后开启新的 service worker 线程,从而优化首屏加载速度
                window.addEventListener('load', () => {
                   // register 方法里面的第一个参数为 Service Worker 要加载的文件;第二个参数 scope 可选,用来指定service worker 控制的内容的子目录
                    navigator.serviceWorker.register('./task-sync.js', { scope: '/worker/' })
                        .then((registration) => {
                            // Service Worker 注册成功
                            console.log('ServiceWorker registration successful with scope: ', registration.scope);
                        }).catch((err) => {
                            // Service Worker 注册失败
                            console.log('ServiceWorker registration failed: ', err);
                        });
                });
            }


            worker.addEventListener('message', (ev) => {
                const message = ev.data.message;

                if ( message.ev === 'click' ) {
                    clickMe();
                } else if ( message.ev === 'input' ) {
                    input.value = message.content;
                }

            });

            btn.onclick = () => {
                if (worker) {
                    worker.controller.postMessage({
                        ev: 'click'
                    });
                } else {
                    console.log('no');
                }
                clickMe();
            };

            input.addEventListener('keyup', (event) => {
                event = event || window.event;

                worker.controller.postMessage({
                    ev: 'input',
                    content: input.value
                });
            });

            function clickMe() {

                if (btn.innerHTML === "click me") {
                    btn.style.backgroundColor = "blue";
                    btn.style.color = "#fff";
                    btn.innerHTML = 'clicked';
                } else {
                    btn.style.backgroundColor = "aqua";
                    btn.style.color = "#000";
                    btn.innerHTML = 'click me';
                }

            }
        })();

    script>

body>
html>

task-sync.js

self.addEventListener('message', (ev) => {
   let promise = self.clients.matchAll()
       .then((clientList) => {
            let senderID = ev.source ? ev.source.id : 'unknown';

            if (!ev.source) {
                console.log("ev.source is null; we don't know the sender of the message!");
            }

            clientList.forEach((client) => {
                if (client.id === senderID) {
                    return ;
                } else {
                    client.postMessage({
                        client: senderID,
                        message: ev.data
                    });
                }
            });
       });

   if (ev.waitUntil) {
       ev.waitUntil(promise);
   }
});

self.addEventListener('activate', (ev) => {
   ev.waitUntil(self.clients.claim());
});

运行本例需要在本机上搭建一个web服务器,或者直接在 WebStorm, PHPStorm… ide 中点击预览。
去见证奇迹吧!!!

点击查看效果

你可能感兴趣的:(javascript,ServiceWorker)