11class PngExporter {
2- static WORKER_STR = function ( href : string ) {
2+ static WORKER_STR = function ( ) {
33 const initLodepng = ( ) => {
4+ // This function will be invoked after receiving the base href via an 'init' message
45 return new Promise ( ( resolve ) => {
5- ( self as any ) . importScripts ( `${ href } static/lib/lodepng/lodepng.js` ) ;
6+ const baseHref = ( self as any ) . __baseHref as string ;
7+ ( self as any ) . importScripts ( `${ baseHref } static/lib/lodepng/lodepng.js` ) ;
68 resolve ( ( self as any ) . lodepng ( {
7- locateFile : ( ) => `${ href } static/lib/lodepng/lodepng.wasm`
9+ locateFile : ( ) => `${ baseHref } static/lib/lodepng/lodepng.wasm`
810 } ) ) ;
911 } ) ;
1012 } ;
@@ -37,13 +39,23 @@ class PngExporter {
3739 } ;
3840
3941 const main = ( ) => {
40- const init = initLodepng ( ) ;
42+ let lodepngPromise : Promise < any > | null = null ;
4143
4244 self . onmessage = async ( message ) => {
43- const lodepng = await init ;
44-
4545 const data = message . data ;
4646
47+ if ( data && data . type === 'init' ) {
48+ ( self as any ) . __baseHref = data . baseHref as string ;
49+ lodepngPromise = initLodepng ( ) ;
50+ return ;
51+ }
52+
53+ if ( ! lodepngPromise ) {
54+ return ;
55+ }
56+
57+ const lodepng = await lodepngPromise ;
58+
4759 // compress
4860 const result = compress ( lodepng , data . words , data . width , data . height ) ;
4961
@@ -62,14 +74,17 @@ class PngExporter {
6274 constructor ( ) {
6375 let receiver : ( message : MessageEvent ) => void = null ;
6476
65- const workerBlob = new Blob ( [ `(${ PngExporter . WORKER_STR } )(' ${ window . location . href . split ( '?' ) [ 0 ] } ' )\n\n` ] , {
77+ const workerBlob = new Blob ( [ `(${ PngExporter . WORKER_STR } )()\n\n` ] , {
6678 type : 'application/javascript'
6779 } ) ;
6880 this . worker = new Worker ( URL . createObjectURL ( workerBlob ) ) ;
6981 this . worker . addEventListener ( 'message' , ( message ) => {
7082 receiver ( message ) ;
7183 } ) ;
7284
85+ const baseHref = new URL ( '.' , window . location . href ) . toString ( ) ;
86+ this . worker . postMessage ( { type : 'init' , baseHref } ) ;
87+
7388 this . receiveCallback = ( resolve ) => {
7489 receiver = ( message ) => {
7590 resolve ( message . data . result ) ;
@@ -93,6 +108,7 @@ class PngExporter {
93108
94109 async export ( filename : string , words : Uint32Array , width : number , height : number ) {
95110 this . worker . postMessage ( {
111+ type : 'encode' ,
96112 words : words ,
97113 width : width ,
98114 height : height
0 commit comments