新玩具 htmz?

前言

今天在 X 上面看到某個名人轉推htmz,這兩天也有上 hacker news

晚上花點時間研究一下機制,做個紀錄

tldr

就噱頭而已,風頭過了就沒了,iframe 效能不好,不過算挺有趣的,奇怪的知識增加了

原理

  • 點擊 a tag 可以把網頁內容指定作用在 iframe
  • 再把 iframe 的內容複製到指定的容器裡面

實作

官網講的漏漏長,反而不容易懂

直接看我簡化的代碼來講解

<!-- index.html -->
<a target="htmz" href="./about.html#demos">Tabs</a>
<div id="demos"></div>
<iframe
    name="htmz"
    hidden
    onload="setTimeout(()=>{
        document.querySelector(contentWindow.location.hash||null)?.replaceWith(...contentDocument.body.childNodes)
    })"
/>

<!-- about.html -->
<div>this is about page</div>
  • a tag 的 target 可以指定作用在 iframe,只是要給他 iframe名稱,這裡是htmz
  • iframe 的屬性hidden,會讓 iframe display: none,不然他會有預設的大小顯示在畫面上
  • onload 後面的代碼是當 iframe 刷新,就是第一次渲染畫面或是點擊a tag去刷新 iframe 時會執行
  • contentWindow.location.hash是 iframe 的網址的hash,點了 a 連結,這時 iframe 的網址就是domain/about.html#demos,取 hash 值就是#demos
  • 所以上面就相當於執行document.querySelector('#demos'),會選取預先就寫好id為demos容器
  • contentDocument.body.childNodes是 iframe 那個內容的node object,也就是about.html的內容
  • 再那來取代<div id="demos">容器的內容,Magic
  • 還有就是要同源,same origin才能這樣搞,而且 iframe 效能比較不好,上不了大廳的東西