Blazor WebAssembly的初次訪問慢的優化

Blazor WebAssembly初次訪問需要加載很多dll,體積較大,因此第一次加載比較慢。

針對此問題Microsoft提供了優化方案:壓縮

https://learn.microsoft.com/zh-cn/aspnet/core/blazor/host-and-deploy/webassembly?view=aspnetcore-6.0#compression-1

gzip壓縮

首先通過nginx開啓gzip壓縮,配置如下

http
    {
     ...
       #是否啓動gzip壓縮,on代表啓動,off代表開啓
        gzip on;
       #如果文件大於1k就啓動壓縮
        gzip_min_length  1k;
       #以16k爲單位,按照原始數據的大小以4倍的方式申請內存空間,一般此項不要修改
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
       #壓縮的等級,數字選擇範圍是1-9,數字越小壓縮的速度越快,消耗cpu就越大
        gzip_comp_level 2;
       #需要壓縮的常見靜態資源
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/octet-stream;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
       #由於nginx的壓縮發生在瀏覽器端而微軟的ie6很坑爹,會導致壓縮後圖片看不見所以該選項是禁止ie6發生壓縮
        gzip_disable   "MSIE [1-6]\.";
    ...
    }

 

重啓nginx

#用來測試配置文件
nginx -t
  
nginx -s reload

 

Brotli壓縮

發佈 Blazor WebAssembly 應用時,將在發佈過程中對輸出內容進行靜態壓縮,從而減小應用的大小,並免去運行時壓縮的開銷。 使用Brotli壓縮算法。

Blazor 依賴於主機提供適當的壓縮文件。 使用 ASP.NET Core 託管項目時,主機項目能夠執行內容協商並提供靜態壓縮文件。 託管 Blazor WebAssembly 獨立應用時,可能需要額外的工作來確保提供靜態壓縮文件。

首先在 wwwroot/index.html 文件中,在 Blazor 的 <script> 標記上將 autostart 設置爲 false:

<script src="_framework/blazor.webassembly.js" autostart="false"></script>

在 Blazor 的 <script> 標記之後和結束 </body> 標記之前,添加以下 JavaScript 代碼 <script> 塊:

<script type="module">
  import { BrotliDecode } from './decode.min.js';
  Blazor.start({
    loadBootResource: function (type, name, defaultUri, integrity) {
      if (type !== 'dotnetjs' && location.hostname !== 'localhost') {
        return (async function () {
          const response = await fetch(defaultUri + '.br', { cache: 'no-cache' });
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          const originalResponseBuffer = await response.arrayBuffer();
          const originalResponseArray = new Int8Array(originalResponseBuffer);
          const decompressedResponseArray = BrotliDecode(originalResponseArray);
          const contentType = type === 
            'dotnetwasm' ? 'application/wasm' : 'application/octet-stream';
          return new Response(decompressedResponseArray, 
            { headers: { 'content-type': contentType } });
        })();
      }
    }
  });
</script>

 

 重新訪問,即可看到訪問速度的提升十分顯著。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章