pill靜態站點動態加載內容的方案


pill 是一個小巧的為了解決靜態站點,web 內容加載問題,通過攔截js 的一些事件通過執行fetch 解決問題

原理說明

  1. 攔截導航事件(鏈接的點擊,以及歷史導航)
  2. 通過fetch 加載請求
  3. 獲取加收到的html 內容
  4. 替換當前頁面的內容

用途

解決我們單頁面應用資源加載的問題(還是希望實現動態內容加載,類似微前端的靈活管理需求)

使用

  • 參考html
<html>
  <head>
    <title>Home</title>
    <script src="https://unpkg.com/pill@1/dist/pill.min.js"></script>
    <style>
      /* global styles */
      #indicator {
        position: fixed;
        top: 0;
        right: 0;
        display: none;
      }
    </style>
  </head>
  <body>
    <div id="indicator">Loading...</div>
    <div id="content">
      <style>/* page styles */</style>
      <!-- page content here -->
    </div>
    <script>
      const indicator = document.querySelector('#indicator')
      pill('#content', {
        onLoading() {
          // Show loading indicator
          indicator.style.display = 'initial'
        },
        onReady() {
          // Hide loading indicator
          indicator.style.display = 'none'
        }
      })
    </script>
  </body>
</html>
  • 提供的方法
    標准調用方法簽名
(selector:string, options:PillOptions) -> void

鈎子:onError() , onLoading(), onMouting(), onReay()
幾個其他配置選項:
fromError() 可以用來自定義錯誤
getKetFromUrl() 通過url 或者加載的key
shouldReload() 決定上次加載的資源是否需要從server 獲取
shouldServe() 處理內容對於連接的處理,是使用原生的還是使用pill提供的

  • 官方的一個demo
    項目結構

     

     

    代碼概述:

     

     

說明

pill 的原理並不難,但是實現的功能確實比較實用的,我們就可以實現類似next.js 以及nuxt.js 的功能,但是需要的東西更少
實際上早期我們可能都會使用ajax+ template 的機制,進行占位內容的替換,pill增強了基於ajax+template 的能力,基於此我們
可以方便的融合多中框架,實現一個簡單的基於客戶端的微前端方案,同時結合下basket.js也是一個很好的使用

參考資料

https://github.com/rumkin/pill
https://github.com/addyosmani/basket.js


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM