🍒 Dynamically inline assets into the DOM using Fetch Injection. https://vhs.codeberg.page/code/fetch-inject/
Go to file
vhs 9fdbecb45c
docs: 📚️ update example usage
2022-03-17 23:51:43 +08:00
.changeset chore(release): 🚀 version package 2022-03-15 22:44:53 +08:00
docs perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
.gitignore perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
.prettierrc perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
CHANGELOG.md chore(release): 🚀 version package 2022-03-15 22:44:53 +08:00
COPYING perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
README.md docs: 📚️ update example usage 2022-03-17 23:51:43 +08:00
fetch-inject.js security: 🔒️ disallow context shifting 2022-03-15 22:43:49 +08:00
module.d.ts feat: add sveltekit support 2022-03-08 21:05:13 +08:00
module.spec.ts perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
package.json chore(release): 🚀 version package 2022-03-15 22:44:53 +08:00
playwright.config.ts perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00
pnpm-lock.yaml build: 📦️ switch from terser to esbuild 2022-03-15 21:18:46 +08:00
test-harness.html perf(breaking): 💥 consolidate to single bundle 2022-03-07 11:47:05 +08:00


Fetch Inject

Latest NPM version Weekly downloads Compressed size Hits per month License

Dynamically inline assets into the DOM using Fetch Injection.

Read the Hacker News discussion.

Overview 🌱

Fetch Inject implements a performance optimization technique called Fetch Injection for managing asynchronous JavaScript dependencies. It works for stylesheets too, and was designed to be extensible for any resource type that can be loaded using fetch.

Use Fetch Inject to dynamically import external resources in parallel (even across the network), and load them into your page in a desired sequence, at a desired time and under desirable runtime conditions.

Because it uses the Fetch API Fetch Inject works alongside Service Workers for creating offline-first, installable progressive web applications and saves bandwidth on metered networks.

Playground 🛝

Try CodePen Playground while referencing the Use Cases provided below.


The two following network waterfall diagrams were produced using Fetch Inject to load the WordPress Twenty Seventeen theme for a performance talk given at WordCamp Ubud 2017. Stats captured over a 4G network using a mobile Wi-Fi hotspot. The left-hand side shows page speed with an unprimed browser cache and the other using Service Worker caching.

Screenshot of network waterfall showing parallel resource loading using Fetch Inject Screenshot of network waterfall showing parallel resource loading using Fetch Inject with Service Workers

Notice with Service Workers (right) most latency occurs waiting for the initial response.

Installation 💾

pnpm add fetch-inject # or yarn, npm i, etc.

For asset pipelines requiring UMD, AMD or CJS check out version 2 and below.

Usage 🌀

Promise<Object[]> fetchInject( inputs[, promise[, options]] )


Resources to fetch. Must be an Array of type USVString or Request objects.
Optional. Promise to await before injecting fetched resources.
Optional. Enables customization of Fetch implementation used.

Return value

A Promise that resolves to an Array of Objects. Each Object contains a list of resolved properties of the Response Body used by the module, e.g.

  blob: { size: 44735, type: "application/javascript" },
  text: "/*!↵ * Bootstrap v4.0.0-alpha.5 ... */"
}, {
  blob: { size: 31000, type: "text/css" },
  text: "/*!↵ * Font Awesome 4.7.0 ... */"

Use Cases 🎯

Use the Playground to try any of these on your own.

Preventing Script Blocking

Problem: External scripts can lead to jank or SPOF if not handled correctly.

Solution: Load external scripts without blocking:


This is a simple case to get you started. Don't worry, it gets better.

Loading Non-critical CSS

Problem: PageSpeed Insights and Lighthouse ding you for loading unnecessary styles on initial render.

Solution: Inline your critical CSS and load non-critical styles asynchronously:

<style>/*! bulma.io v0.4.0 ... */</style>
<script type="module">
  import fetchInject from 'https://www.jsdelivr.com/package/npm/fetch-inject'

See also Suspense below.

Lazyloading Scripts

Problem: You want to load a script in response to a user interaction without affecting your page load times.

Solution: Create an event listener, respond to the event and then destroy the listener.

const el = document.querySelector('details summary')
el.onclick = (evt) => {
  el.onclick = null

Here we are loading the smooth scroll polyfill when a user opens a details element, useful for displaying a collapsed and keyboard-friendly table of contents.

Responding to Asynchronous Scripts

Problem: You need to perform a synchronous operation immediately after an asynchronous script is loaded.

Solution: You could create a script element and use the async and onload attributes. Or you could...

]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)

Ordering Script Dependencies

Problem: You have several scripts that depend on one another and you want to load them all asynchronously, in parallel, without causing race conditions.

Solution: Pass fetchInject to itself as a second argument, forming a promise recursion:

], fetchInject([

Managing Asynchronous Dependencies

Problem: You want to load some dependencies which require some dependencies, which require some dependencies. You want it all in parallel, and you want it now.

Solution: You could scatter some links into your document head, blocking initial page render, bloat your application bundle with scripts the user might not actually need. Or you could...

const tether = ['https://cdn.jsdelivr.net/tether/1.4.0/tether.min.js']
const drop = ['https://cdn.jsdelivr.net/drop/1.4.2/js/drop.min.js']
const tooltip = [
fetchInject(tooltip, fetchInject(drop, fetchInject(tether)))
  .then(() => {
    new Tooltip({
      target: document.querySelector('h1'),
      content: "You moused over the first <b>H1</b>!",
      classes: 'tooltip-theme-arrows',
      position: 'bottom center'

What about jQuery dropdown menus? Sure why not...

], fetchInject([
], fetchInject([
], fetchInject([

Loading and Handling Composite Libraries

Problem: You want to deep link to gallery images using PhotoSwipe without slowing down your page.

Solution: Download everything in parallel and instantiate when finished:

const container = document.querySelector('.pswp')
const items = JSON.parse({{ .Params.gallery.main | jsonify }})
]).then(() => {
  const gallery = new PhotoSwipe(container, PhotoSwipeUI_Default, items)

This example turns TOML into JSON, parses the object, downloads all of the PhotoSwipe goodies and then activates the PhotoSwipe gallery immediately when the interface is ready to be displayed.


Problem: You're experiencing a flash of unstyled content when lazy-loading page resources.

Solution: Hide the content until your styles are ready:

const pageReady = new Promise((resolve, reject) => {
  document.onreadystatechange = () => {
    document.readyState === "complete" && resolve(document);

], pageReady).then(() => (document.body.style.visibility = 'visible'));

A/B Testing

Problem: You want to run A/B tests and track the winning experience.

Solution: Dynamically import Fetch Inject, and display and report the winning experience.

<script type="module">
  localStorage.setItem('experience', ['test-a.css', 'test-a.js']);
  const experience = localStorage.getItem('experience');
  const analytics = 'analytics.min.js';

    .then((module) => {
        .then((injections) => {
            testGroup: experience, // "test-a.css,test-a.js"
            waitTime: console.timeLog('page-time') // "0.231953125 ms"
            extraData: injections // [ Blob {size: 7889, ...} ]
          document.onclose = _ => analytics.track({
            testGroup: experience,
            pageTime: console.endTime('page-time') // "8.29296875 ms"
        .catch((errors) => analytics.error(errors))

Use alongside Suspense for a winning combination.


As of version 3.1.0 Fetch Inject supports use with SvelteKit. Use it inside your load functions to run Fetch requests client- and server-side. Or drop it inside your hooks in order to inject resources into the document like so:

export const handle: Handle = sequence(
  async ({ event, resolve }) => {
    const response = await resolve(event);
    const [flexsearch] = await fetchInject([

    const body = await response.text();
    return new Response(
      body.replace('</body>', `<script>${flexsearch.text}</script></body>`),
  /* snip */

The above will inject FlexSearch into every page on the site.

Custom Fetch

Fetch Inject 3.0.0 quietly introduced a new feature allowing control the Fetch implementation used. SvelteKit provides its own server-side Fetch implementation, which you can now override when fetching resources with Fetch Inject:

], Promise.resolve(), { fetch: globalThis.fetch })

The above replaces the SvelteKit fetch implementation with native fetch.

Supported Browsers 🔮

All browsers with support for Fetch and Promises.

Progressive Enhancement 🛟

You don't need to polyfill fetch for older browsers when they already know how to load external scripts. Give them a satisfactory fallback experience instead.

In your document head get the async loading started right away if the browser supports it:

(function () {
  if (!window.fetch) return;
  ], fetchInject([

Then, before the close of the document body (if JS) or in the head (if CSS), provide the traditional experience:

(function () {
  if (window.fetch) return;
  document.write('<script src="/js/bootstrap.min.js"><\/script>');
  document.write('<script src="/js/jquery.slim.min.jss"><\/script>');
  document.write('<script src="/js/tether.min.js"><\/script>');

This is entirely optional, but a good practice unless you're going full hipster.

WordPress Plugin 🚀

Fetch Inject has been built into a WordPress plugin, enabling Fetch Injection to work within WordPress. Initial testing shows Fetch Injection enables WordPress to load pages 300% faster than conventional methods.

Hyperdrive WordPress Plugin

Access the plugin from the Hyperdrive repo and see the related Hacker Noon post for more details.

Rights ⚖️

Fetch Inject - Dynamically inline assets into the DOM using Fetch Injection.
Copyright (C) 2017-2019, 2022  VHS <vhsdev@tutanota.com> (https://vhs.codeberg.page)

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

See the file COPYING in the source for full license text.