i12n / i12n.github.io

3 stars 0 forks source link

HTML5 #8

Open i12n opened 8 years ago

i12n commented 8 years ago

Page Visibility

当用户进行最小化、切换tab、锁屏等操作离开当前页面之后,这时用户虽然不再关注这个页面,但是页面上的一些行为依然会像之前一样执行。例如一个视频播放页,将其最小化之后,视频如果依然播放下去,这无疑会造成资源的浪费。如果开发人员能够获得页面的是否可见的状态,就可以采取相应的策略取消或更改页面的行为,为此 HTML 提供了Page Visibility。

Page Visibility 是一个用于检查页面是否处于可见 (visibility) 状态的 API. 它提供了两个属性,document.hiddendocument.visibilityState。当页面处于激活状态 document.hidden 的值为 false , 否则 它的值为 true. document.visibilityState 可以是以下值:

visible: the page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window. hidden : the page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active. prerender : the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). The document may start in this state, but will never transition to it from another value. Note: browser support is optional. unloaded: the page is being unloaded from memory. Note: browser support is optional.

另外,还提供了一个事件 visibilitychange,当页面可见状态发生变化,就会触发 visibilitychange 事件。

document.addEventListener('visibilitychange', function() {
      console.log(document['hidden']);
      console.log(document['visibilityState']);
});

Page Visibility 好处就是节省资源.

更多资源 http://www.w3.org/TR/page-visibility/?csw=1#dom-document-visibilitystate http://www.html5rocks.com/en/tutorials/pagevisibility/intro/ https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API http://blog.teamtreehouse.com/an-introduction-to-the-page-visibility-api https://github.com/amfe/article/issues/26

i12n commented 8 years ago

<dialog>

<dialog> 可以用于实现弹出对话框。 用法:

<dialog open>
    <p>Hi, this is a dialog!</p>
</dialog>

<dialog> 可以内嵌 <form>元素,并且将 <form> 设置 method="dialog" 之后,当点击 submit 按钮,<dialog> 会被 close.

<dialog> 元素与 HTMLDialogElement DOM接口对应,HTMLDialogElement 提供以下方法:

HTMLDialogElement 具有以下属性:

  <button id="open-btn">open dialog</button>
  <dialog open id="show-dialog">
    <p>Hi, this is a dialog!</p>
    <form method="dialog">
      <input type="submit" value="close dialog" />
    </form>
  </dialog>
  <script type="text/javascript">
    var showDialog = document.getElementById('show-dialog');
    var openBtn = document.getElementById('open-btn');
    openBtn.addEventListener('click', function() {
      showDialog.showModal();
    });
    showDialog.addEventListener('close', function() {
      console.log(showDialog.returnValue); // "close dialog"
    });
  </script>

<dialog> 遮罩的样式可以通过 ::backdrop 来设置,例如

dialog::backdrop {
      background:rgba(0,0,0,0.5);
}

完整代码片段

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLDialogElement https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop http://blog.teamtreehouse.com/a-preview-of-the-new-dialog-element

i12n commented 8 years ago

MutationObserver

MutationObserver可以用于检测dom的变化,当dom发生变化时会触发回调函数。需要注意的是,为了防止dom频繁变化时调用回调函数引起卡顿现象,MutationObserver 会将dom的一些变动存于数组中统一处理,并不是只要dom发生变化就执行回调函数。

MutationObserver 构造的实例对象需要设置一个回调函数,当dom发生变化时会调用这个函数,如下:

var observer  = new WebKitMutationObserver(
     function callback
);

MutationObserve 实例对象进行监听需要调用 observe 方法,observe 方法的需要的参数有两个, 目标dom节点和配置信息,如下:

void observe(
     Node target,
     MutationObserverInit options
);

options 配置可有如下选项:

Property Description
childList Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.
attributes Set to true if mutations to target's attributes are to be observed.
characterData Set to true if mutations to target's data are to be observed.
subtree Set to true if mutations to not just target, but also target's descendants are to be observed.
attributeOldValue Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValue Set to true if characterData is set to true and target's data before the mutation needs to be recorded.
attributeFilter Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.

以下是完整的实例:

var observer = new WebKitMutationObserver(function(mutations) {
    // mutations 是 dom 多次变动信息
    mutations.forEach(function(mutation) {
        var addedNodes = mutation.addedNodes;
        for (var i = 0; i < addedNodes.length; i++) {
            var nodeTagName = addedNodes[i].tagName;
            console.log(nodeTagName);
        }
    });
});

var observerConfig = {
    childList: true,
};

var targetNode = document.getElementById('#node');
observer.observe(targetNode, observerConfig);

参考文档: MutationObserver -- MDN

i12n commented 7 years ago

Server-Send Events

服务器推送事件(Server-sent Events)是 HTML 5 规范中的一个组成部分,可以用来从服务端实时推送数据到浏览器端。它的主要特点是,数据传送是单向的,只能从服务端向浏览器推送数据,浏览器可以订阅服务端推送来的数据。

var http = require('http');
var sys = require('sys');
var fs = require('fs');

http.createServer(function(req, res) {
  //debugHeaders(req);

  if (req.headers.accept && req.headers.accept == 'text/event-stream') {
    if (req.url == '/events') {
      sendSSE(req, res);
    } else {
      res.writeHead(404);
      res.end();
    }
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(fs.readFileSync(__dirname + '/sse-node.html'));
    res.end();
  }
}).listen(8000);

function sendSSE(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  var id = (new Date()).toLocaleTimeString();

  // Sends a SSE every 5 seconds on a single connection.
  setInterval(function() {
    constructSSE(res, id, (new Date()).toLocaleTimeString());
  }, 5000);

  constructSSE(res, id, (new Date()).toLocaleTimeString());
}

function constructSSE(res, id, data) {
  res.write('id: ' + id + '\n');
  res.write("data: " + data + '\n\n');
}

function debugHeaders(req) {
  sys.puts('URL: ' + req.url);
  for (var key in req.headers) {
    sys.puts(key + ': ' + req.headers[key]);
  }
  sys.puts('\n\n');
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>
    <script>
        var source = new EventSource('/events');
        source.onmessage = function(e) {
            document.body.innerHTML += e.data + '<br>';
        };
    </script>
</body>
</html>
~

https://www.html5rocks.com/en/tutorials/eventsource/basics/