🍒 Dynamically inline assets into the DOM using Fetch Injection https://habd.as/code/fetch-inject/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Josh Habdas e632f200e9
🛠 Switch release tools
1 year ago
docs docs(readme): purge project-related github links 3 years ago
src 💄 Clean up linters 1 year ago
.gitignore build($npm): add package lock 3 years ago
.npmignore chore(license): update to less encumbered license 3 years ago
CHANGELOG.md chore(release): 2.0.4 2 years ago
LICENSE refactor(npm/package): update canonical source links 2 years ago
README.md docs(readme): add related project 2 years ago
package.json 🛠 Switch release tools 1 year ago
rollup.config.js 🏗 Update dev dependencies 1 year ago
yarn.lock 🛠 Switch release tools 1 year ago


Fetch Inject

Dynamically inline assets into the DOM using Fetch Injection.

Latest NPM version Zero dependencies Compressed size NPM downloads per month Hits per month via jsDelivr CDN License

Read the Hacker News discussion.


Fetch Inject implements a Web performance optimization technique known as 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 JavaScript and CSS 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 Fetch API Fetch Inject works alongside Service Workers enabling offline-first applications and improving performance in bandwidth-restricted environments.


Try CodePen Playground. Reference the Use Cases to enhance your understanding of what Fetch Injection can do for you.


The 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 hotspot. One shows the speed of the page load with an unprimed browser cache and the other using Service Worker caching. Notice with Service Workers most of the perceived latency with occurs simply waiting for the HTML response to load.

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


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


This defines the resources you wish to fetch. It must be an Array containing elements of type USVString or Request.
Optional. A Promise to await before injecting fetched resources.

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 ... */"


Fetch Inject is available on NPM and CDN. It ships in the following flavors: IIFE, UMD and ES6.

Save latest minified UMD bundle to a file with cURL:

curl -o fetch-inject.umd.min.js https://cdn.jsdelivr.net/npm/fetch-inject

Add all three bundles to a Yarn package:

yarn add fetch-inject --production

Install the latest 1.7 patch release using NPM:

npm i -p fetch-inject@~1.7

Download the 1.8.1 ES6 module bundle using fetch:


For asset pipelines requiring vanilla AMD or CJS modules see the Development section.

Use Cases

Try the Fetch Inject Playground while referencing the following use cases to enhance your understanding of what this library can do for you.

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>

Unlike loadCSS, Fetch Inject is smaller, doesn't use callbacks and ships a minifed UMD build for interop with CommonJS.

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.

Supported Browsers

All browsers with support for Fetch and Promises. Because Fetch is a newer Web standard, we will help identify, open and track issues against browser implementations as they arise while specs are being finalized.

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.


  1. Clone the repo.
  2. Install dev dependencies.
  3. Execute npm run for a listing of available commands.

If you need vanilla AMD or CJS modules, update activeConfigs in rollup.config.js.


Please create a new issue for bugs and enhancement requests and accompany any bug with a reduced test case.

When sending pull requests please use npm run commit to create a Conventional Commit message. Pulls should be squashed into a single commit prior to review and, ideally, should PR against a backing issue.

For support use Stack Overflow and tag your question with fetch-api.

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 beta from the Hyperdrive repo and see the related Hacker Noon post for more details.


zlib License

Copyright (C) 2017–2018 Josh Habdas jhabdas@protonmail.com