|
21 | 21 | try { importScripts('https://cdn.jsdelivr.net/npm/[email protected]/elasticlunr.min.js'); } |
22 | 22 | catch { importScripts(abs('/elasticlunr.min.js')); } |
23 | 23 | |
24 | | - /* 2 — load a single index (remote → local) */ |
| 24 | + /* 2 — decompress gzip data */ |
| 25 | + async function decompressGzip(arrayBuffer){ |
| 26 | + if(typeof DecompressionStream !== 'undefined'){ |
| 27 | + /* Modern browsers: use native DecompressionStream */ |
| 28 | + const stream = new Response(arrayBuffer).body.pipeThrough(new DecompressionStream('gzip')); |
| 29 | + const decompressed = await new Response(stream).arrayBuffer(); |
| 30 | + return new TextDecoder().decode(decompressed); |
| 31 | + } else { |
| 32 | + /* Fallback: use pako library */ |
| 33 | + if(typeof pako === 'undefined'){ |
| 34 | + try { importScripts('https://cdn.jsdelivr.net/npm/[email protected]/dist/pako.min.js'); } |
| 35 | + catch(e){ throw new Error('pako library required for decompression: '+e); } |
| 36 | + } |
| 37 | + const uint8Array = new Uint8Array(arrayBuffer); |
| 38 | + const decompressed = pako.ungzip(uint8Array, {to: 'string'}); |
| 39 | + return decompressed; |
| 40 | + } |
| 41 | + } |
| 42 | +
|
| 43 | + /* 3 — load a single index (remote → local) */ |
25 | 44 | async function loadIndex(remote, local, isCloud=false){ |
26 | 45 | let rawLoaded = false; |
27 | 46 | if(remote){ |
| 47 | + /* Try compressed version first */ |
28 | 48 | try { |
29 | | - const r = await fetch(remote,{mode:'cors'}); |
30 | | - if (!r.ok) throw new Error('HTTP '+r.status); |
31 | | - importScripts(URL.createObjectURL(new Blob([await r.text()],{type:'application/javascript'}))); |
32 | | - rawLoaded = true; |
33 | | - } catch(e){ console.warn('remote',remote,'failed →',e); } |
| 49 | + const gzUrl = remote + '.gz'; |
| 50 | + const r = await fetch(gzUrl,{mode:'cors'}); |
| 51 | + if (r.ok) { |
| 52 | + const compressed = await r.arrayBuffer(); |
| 53 | + const text = await decompressGzip(compressed); |
| 54 | + importScripts(URL.createObjectURL(new Blob([text],{type:'application/javascript'}))); |
| 55 | + rawLoaded = true; |
| 56 | + console.log('Loaded compressed',gzUrl); |
| 57 | + } |
| 58 | + } catch(e){ console.warn('compressed',remote+'.gz','failed →',e); } |
| 59 | + |
| 60 | + /* Fall back to uncompressed if compressed failed */ |
| 61 | + if(!rawLoaded){ |
| 62 | + try { |
| 63 | + const r = await fetch(remote,{mode:'cors'}); |
| 64 | + if (!r.ok) throw new Error('HTTP '+r.status); |
| 65 | + importScripts(URL.createObjectURL(new Blob([await r.text()],{type:'application/javascript'}))); |
| 66 | + rawLoaded = true; |
| 67 | + console.log('Loaded uncompressed',remote); |
| 68 | + } catch(e){ console.warn('remote',remote,'failed →',e); } |
| 69 | + } |
34 | 70 | } |
35 | 71 | if(!rawLoaded && local){ |
36 | 72 | try { importScripts(abs(local)); rawLoaded = true; } |
|
0 commit comments