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 <mihai@tailscale.com>
This commit is contained in:
Mihai Parparita
2022-08-02 15:02:26 -07:00
committed by Mihai Parparita
parent f04bc31820
commit 52d769d35c
3 changed files with 18 additions and 1 deletions

View File

@@ -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
}