HTTP Preload / Resource Hints / Early Hints support for Node.js server frameworks like express, koa and local-web-server.
npm install --save-dev preload-middleware
Prepare a preload manifest file, e.g.
{
"manifestVersion": 1,
"resources": {
"/index.html": {
"Link": [
"<./assets/index.css>;rel=preload;as=style",
"<./src/foobar.js>;rel=modulepreload",
"</lib/foo.js>;rel=modulepreload",
"</lib/bar.js>;rel=modulepreload",
"<./src/qux.js>;rel=modulepreload;fetchpriority=low"
]
},
"/alternate.xhtml": {
"Link": "<./src/foobar.js>;rel=modulepreload, </lib/foo.js>;rel=modulepreload, </lib/bar.js>;rel=modulepreload, <./src/qux.js>;rel=modulepreload;fetchpriority=low"
}
}
}
npm install --save-dev express
import express from 'express';
import {serveStaticPreload} from 'preload-middleware';
let app = express();
app.use('/', express.static('./public', {
setHeaders: serveStaticPreload({
manifestFile: './config/preload.json',
watch: true,
}),
}));
npm install --save-dev koa koa-static
import Koa from 'koa';
import koaStatic from 'koa-static';
import {serveStaticPreload} from 'preload-middleware';
let app = new Koa();
app.use(koaStatic('./public', {
setHeaders: serveStaticPreload({
manifestFile: './config/preload.json',
watch: true,
}),
}));
Edit lws.config.js
export default {
port: 443,
directory: './public',
stack: [
'lws-request-monitor',
'lws-compress',
'lws-mime',
'lws-range',
'preload-middleware', // put preload-middleware before lws-static
'lws-static',
'lws-index',
],
// options for preload-middleware
preload: {
manifestFile: './config/preload.json'
},
};
-
manifestFile
:stringpath to preload manifest file
-
watch
:boolean defaultfalse
whether to watch the manifest file and hot reload
-
index
:string default"index.html"
(only for local-web-server)should be same as serve-index, or koa-static
-
prefersEarlyHints
:boolean defaultfalse
if configured to be
true
, and user-agent supports 103 Early Hints, then links will be sent with status 103. Note: Chrome doesn't yet support 103 Early Hints over HTTP/2, see https://issues.chromium.org/issues/40496584
You can find a complete example application in preload-middleware GitHub repo.