Просмотр исходного кода

cmd/tsconnect: prefetch main.wasm when serving

Avoids waterfalling of requests from the file (its load is triggered
from JavaScript).

Also has other cleanups to index.html, adding a <title> and moving the
<script> to being loaded sooner (but still not delaying page rendering
by using the defer attribute).

Fixes #5141
Fixes #5135

Signed-off-by: Mihai Parparita <[email protected]>
Mihai Parparita 3 лет назад
Родитель
Сommit
52d769d35c
3 измененных файлов с 18 добавлено и 1 удалено
  1. 3 0
      cmd/tsconnect/common.go
  2. 2 1
      cmd/tsconnect/index.html
  3. 13 0
      cmd/tsconnect/serve.go

+ 3 - 0
cmd/tsconnect/common.go

@@ -119,6 +119,9 @@ func runYarn(args ...string) error {
 // from entry points to hashed file names.
 type EsbuildMetadata struct {
 	Outputs map[string]struct {
+		Inputs map[string]struct {
+			BytesInOutput int64 `json:"bytesInOutput"`
+		} `json:"inputs,omitempty"`
 		EntryPoint string `json:"entryPoint,omitempty"`
 	} `json:"outputs,omitempty"`
 }

+ 2 - 1
cmd/tsconnect/index.html

@@ -3,7 +3,9 @@
   <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Tailscale Connect</title>
     <link rel="stylesheet" type="text/css" href="dist/index.css" />
+    <script src="dist/index.js" defer></script>
   </head>
   <body class="flex flex-col h-screen overflow-hidden">
     <div class="bg-gray-100 border-b border-gray-200 pt-4 pb-2">
@@ -38,6 +40,5 @@
         enabled. Give it a try!
       </div>
     </div>
-    <script src="dist/index.js"></script>
   </body>
 </html>

+ 13 - 0
cmd/tsconnect/serve.go

@@ -83,10 +83,19 @@ func generateServeIndex(distFS fs.FS) ([]byte, error) {
 		return nil, fmt.Errorf("Could not parse esbuild-metadata.json: %w", err)
 	}
 	entryPointsToHashedDistPaths := make(map[string]string)
+	mainWasmPath := ""
 	for outputPath, output := range esbuildMetadata.Outputs {
 		if output.EntryPoint != "" {
 			entryPointsToHashedDistPaths[output.EntryPoint] = path.Join("dist", outputPath)
 		}
+		if path.Ext(outputPath) == ".wasm" {
+			for input := range output.Inputs {
+				if input == "src/main.wasm" {
+					mainWasmPath = path.Join("dist", outputPath)
+					break
+				}
+			}
+		}
 	}
 
 	indexBytes := rawIndexBytes
@@ -96,6 +105,10 @@ func generateServeIndex(distFS fs.FS) ([]byte, error) {
 			indexBytes = bytes.ReplaceAll(indexBytes, []byte(defaultDistPath), []byte(hashedDistPath))
 		}
 	}
+	if mainWasmPath != "" {
+		mainWasmPrefetch := fmt.Sprintf("</title>\n<link rel='preload' as='fetch' crossorigin='anonymous' href='%s'>", mainWasmPath)
+		indexBytes = bytes.ReplaceAll(indexBytes, []byte("</title>"), []byte(mainWasmPrefetch))
+	}
 
 	return indexBytes, nil
 }