posthtml-plugin-link-preload

1.0.0 • Public • Published

PostHTML Plugin Link Preload

This plugin sets up preload/prefetch tags and headers.

Before:

<html>
  <head>
  ...
  </head>
  <body>
    <div>... component...</div>
    <script
      data-link-preload="preload"
      data-link-preload-type="markup"
      src="component.js"
    ></script> 
  </body>
</html>

After:

<html>
  <head>
    <link rel="preload" href="component.js" as="script">
  ...
  </head>
  <body>
    <div>... component...</div>
    <script
      data-link-preload="preload"
      data-link-preload-type="markup"
      src="component.js"
    ></script> 
  </body>
</html>

Install

npm i posthtml posthtml-plugin-link-preload

Usage

const fs = require('fs');
const posthtml = require('posthtml');
const posthtmlPluginLinkPreload = require('posthtml-plugin-link-preload');
 
posthtml()
    .use(posthtmlPluginLinkPreload({}))
    .process(html)
    .then(result => fs.writeFileSync('./after.html', result.html));

Options

  • attr: the html attribute name to use (optional, default: data-link-preload)
  • addHeader: a function that is called with 2 arguments: headerName, headerValue (optional, default: an empty function)

Attribute values

data-link-preload:

  • preload: enable resource preload (default)
  • prefetch: enable resource prefetch

data-link-preload-type:

Where to use it

These features can be use on these tags with either srv or href tag:

  • script
  • link with rel stylesheet
  • audio
  • video
  • track
  • img
  • iframe
  • embed
  • object

Adding headers

Here is an example using Expressjs:

app.get('/', async (req, res) => {
  const html = `
<html>
  <head></head>
  <body>
    <div>... component...</div>
    <script
      data-link-preload="preload"
      data-link-preload-type="header"
      src="component.js"
    ></script>
  </body>
</html>`
 
  const addHeader = (name, content) => {
    // name: link
    // content: '<component.js>; rel=preload; as=script
    res.set(name, content)
  }
 
  const result = await posthtml()
    .use(posthtmlPluginLinkPreload({ addHeader }))
    .process(html)
 
  res.send(result.html)
})

Package Sidebar

Install

npm i posthtml-plugin-link-preload

Weekly Downloads

300

Version

1.0.0

License

MIT

Unpacked Size

11.4 kB

Total Files

9

Last publish

Collaborators

  • sithmel