Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fetch-inject

Package Overview
Dependencies
Maintainers
1
Versions
65
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetch-inject - npm Package Compare versions

Comparing version 2.0.4 to 3.0.0

COPYING

61

package.json
{
"name": "fetch-inject",
"version": "2.0.4",
"version": "3.0.0",
"description": "Dynamically inline assets into the DOM using Fetch Injection.",
"author": "Josh Habdas <jhabdas@protonmail.com> (https://habd.as)",
"module": "dist/fetch-inject.es.js",
"main": "dist/fetch-inject.umd.js",
"author": "VHS <vhsdev@tutanota.com> (https://vhs.codeberg.page)",
"keywords": [
"fetch",
"inject",
"import",
"async",
"promise",
"script"
],
"homepage": "https://habd.as/code/fetch-inject/",
"homepage": "https://vhs.codeberg.page/code/fetch-inject/",
"repository": {
"type": "git",
"url": "https://git.habd.as/jhabdas/fetch-inject.git"
"url": "https://codeberg.org/vhs/fetch-inject.git"
},
"devDependencies": {
"@changesets/cli": "^2.21.1",
"@playwright/test": "^1.19.2",
"miniserve": "^0.2.1",
"prettier": "^2.5.1",
"terser": "^5.12.0"
},
"files": [
"COPYING",
"docs",
"fetch-inject.min.js",
"fetch-inject.js",
"module.d.ts",
"README.md"
],
"type": "module",
"browser": "fetch-inject.min.js",
"typings": "module.d.ts",
"license": "Zlib",
"scripts": {
"build": "rollup -c",
"clean": "rimraf dist",
"test": "while true; do head -n 100 /dev/urandom; sleep 0.1; done | hexdump -C | grep 'ca fe'",
"lint": "standard",
"release": "standard-version -s"
"dev": "miniserve --index test-harness.html",
"build": "terser fetch-inject.js --compress --mangle --output fetch-inject.min.js",
"package": "pnpm lint && pnpm build && pnpm test",
"test": "PW_EXPERIMENTAL_TS_ESM=1 playwright test",
"lint": "prettier --ignore-path .gitignore --check **/*.{js,ts,html}",
"format": "prettier --ignore-path .gitignore --write **/*.{js,ts,html}",
"changeset": "changeset"
},
"standard-version": {
"scripts": {
"prerelease": "npm run lint",
"postbump": "npm run build"
}
},
"devDependencies": {
"rimraf": "^2.6.3",
"rollup": "^1.6.0",
"rollup-plugin-license": "^0.8.1",
"rollup-plugin-terser": "^4.0.4",
"standard": "^12.0.1",
"standard-version": "^5.0.1"
},
"license": "Zlib"
}
"readme": "# Fetch Inject \n\n[![Latest NPM version](https://flat.badgen.net/npm/v/fetch-inject)](https://npmjs.com/fetch-inject)\n[![Weekly downloads](https://flat.badgen.net/npm/dw/fetch-inject)](https://npmjs.com/fetch-inject)\n[![Compressed size](https://flat.badgen.net/bundlephobia/minzip/fetch-inject)](https://bundlephobia.com/package/fetch-inject)\n[![Hits per month](https://flat.badgen.net/jsdelivr/hits/npm/fetch-inject)](https://www.jsdelivr.com/package/npm/fetch-inject)\n[![License](https://flat.badgen.net/npm/license/fetch-inject)](https://codeberg.org/vhs/fetch-inject)\n\nDynamically inline assets into the DOM using [Fetch Injection](https://vhs.codeberg.page/post/managing-async-dependencies-javascript/).\n\nRead the [**Hacker News discussion**](https://news.ycombinator.com/item?id=14380191).\n\n## Overview 🌱\n\nFetch Inject implements a performance optimization technique called [Fetch Injection](https://vhs.codeberg.page/post/managing-async-dependencies-javascript/) 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`](https://devdocs.io/dom-fetch/).\n\nUse 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.\n\nBecause it uses the [Fetch API](http://devdocs.io/dom/fetch_api) Fetch Inject works alongside [Service Workers](http://devdocs.io/dom-service-workers/) for creating offline-first, installable progressive web applications and saves bandwidth on metered networks.\n\n## Playground 🛝\n\nTry [CodePen Playground](https://codepen.io/vhsdev/pen/QWOoJqG?editors=0012) while referencing the [Use Cases](#use-cases) provided below.\n\n## Performance ⚡️\n\nThe 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.\n\n<p>\n <img src=\"docs/fetch-inject-unprimed-cache.webp\" title=\"Fetch Inject Unprimed Cache\" width=\"48%\" alt=\"Screenshot of network waterfall showing parallel resource loading using Fetch Inject\">\n <img src=\"docs/fetch-inject-serviceworker-caching.webp\" width=\"48%\" title=\"Fetch Inject Service Worker Caching\" alt=\"Screenshot of network waterfall showing parallel resource loading using Fetch Inject with Service Workers\">\n</p>\n\nNotice with Service Workers (right) most latency occurs waiting for the initial response.\n\n## Installation 💾\n\n```sh\npnpm add fetch-inject # or yarn, npm i, etc.\n```\n\nFor asset pipelines requiring UMD, AMD or CJS check out version 2 and below.\n\n## Usage 🌀\n\n Promise<Object[]> fetchInject( inputs[, promise] )\n\n### Parameters\n\n<dl>\n<dt>inputs<dd>Resources to fetch. Must be an <code>Array</code> of type <a target=\"devdocs\" href=\"http://devdocs.io/dom/usvstring\"><code>USVString</code></a> or <a target=\"devdocs\" href=\"http://devdocs.io/dom/request\"><code>Request</code></a> objects.\n<dt>promise<dd>Optional. <a target=\"devdocs\" href=\"http://devdocs.io/javascript/global_objects/promise\"><code>Promise</code></a> to await before injecting fetched resources.\n</dl>\n\n### Return value\n\nA [`Promise`](http://devdocs.io/javascript/global_objects/promise) that resolves to an `Array` of `Object`s. Each `Object` contains a list of resolved properties of the [`Response`](http://devdocs.io/dom/response) [`Body`](http://devdocs.io/dom/body) used by the module, e.g.\n\n```js\n[{\n blob: { size: 44735, type: \"application/javascript\" },\n text: \"/*!↵ * Bootstrap v4.0.0-alpha.5 ... */\"\n}, {\n blob: { size: 31000, type: \"text/css\" },\n text: \"/*!↵ * Font Awesome 4.7.0 ... */\"\n}]\n```\n\n## Use Cases 🎯\n\n[Use the Playground](#playground) to try any of these on your own.\n\n### Preventing Script Blocking\n\n**Problem:**\nExternal scripts can lead to [jank](http://jankfree.org/) or [SPOF](https://www.stevesouders.com/blog/2010/06/01/frontend-spof/) if not handled correctly.\n\n**Solution:**\nLoad external scripts [without blocking](https://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/):\n\n```html\nfetchInject([\n 'https://cdn.jsdelivr.net/npm/flexsearch/dist/flexsearch.bundle.min.js'\n])\n```\n\nThis is a simple case to get you started. Don't worry, it gets better.\n\n### Loading Non-critical CSS\n\n**Problem:**\n[PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/) and [Lighthouse](https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk) ding you for loading unnecessary styles on initial render.\n\n**Solution:**\nInline your critical CSS and load [non-critical styles](https://gist.github.com/scottjehl/87176715419617ae6994) asynchronously:\n\n```html\n<style>/*! bulma.io v0.4.0 ... */</style>\n<script type=\"module\">\nfetchInject([\n '/css/non-critical.css',\n 'https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css'\n])\n</script>\n```\n\nUnlike [`loadCSS`](https://github.com/filamentgroup/loadCSS/), Fetch Inject is smaller, doesn't use callbacks and ships a minifed UMD build for interop with CommonJS.\n\n### Lazyloading Scripts\n\n**Problem:**\nYou want to load a script in response to a user interaction without affecting your page load times.\n\n**Solution:**\nCreate an event listener, respond to the event and then destroy the listener.\n\n```js\nconst el = document.querySelector('details summary')\nel.onclick = (evt) => {\n fetchInject([\n 'https://cdn.jsdelivr.net/smooth-scroll/10.2.1/smooth-scroll.min.js'\n ])\n el.onclick = null\n}\n```\n\nHere we are loading the smooth scroll polyfill when a user opens a [details](http://devdocs.io/html/element/details) element, useful for displaying a collapsed and keyboard-friendly table of contents.\n\n### Responding to Asynchronous Scripts\n\n**Problem:**\nYou need to perform a synchronous operation immediately after an asynchronous script is loaded.\n\n**Solution:**\nYou could create a `script` element and use the [`async`](http://devdocs.io/html/attributes#async-attribute) and `onload` attributes. Or you could...\n\n```js\nfetchInject([\n 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'\n]).then(() => {\n console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)\n})\n```\n\n### Ordering Script Dependencies\n\n**Problem:**\nYou have several scripts that depend on one another and you want to load them all asynchronously, in parallel, without causing race conditions.\n\n**Solution:**\nPass `fetchInject` to itself as a second argument, forming a promise recursion:\n\n```js\nfetchInject([\n 'https://npmcdn.com/bootstrap@4.0.0-alpha.5/dist/js/bootstrap.min.js'\n], fetchInject([\n 'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',\n 'https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js'\n]))\n```\n\n### Managing Asynchronous Dependencies\n\n**Problem:**\nYou want to load some dependencies which require some dependencies, which require some dependencies. You want it all in parallel, and you want it now.\n\n**Solution:**\nYou could scatter some `link`s into your document head, blocking initial page render, bloat your application bundle with scripts the user might not actually need. Or you could...\n\n```js\nconst tether = ['https://cdn.jsdelivr.net/tether/1.4.0/tether.min.js']\nconst drop = ['https://cdn.jsdelivr.net/drop/1.4.2/js/drop.min.js']\nconst tooltip = [\n 'https://cdn.jsdelivr.net/tooltip/1.2.0/tooltip.min.js',\n 'https://cdn.jsdelivr.net/tooltip/1.2.0/tooltip-theme-arrows.css'\n]\nfetchInject(tooltip, fetchInject(drop, fetchInject(tether)))\n .then(() => {\n new Tooltip({\n target: document.querySelector('h1'),\n content: \"You moused over the first <b>H1</b>!\",\n classes: 'tooltip-theme-arrows',\n position: 'bottom center'\n })\n })\n```\n\nWhat about jQuery dropdown menus? Sure why not...\n\n```js\nfetchInject([\n '/assets/js/main.js'\n], fetchInject([\n '/assets/js/vendor/superfish.min.js'\n], fetchInject([\n '/assets/js/vendor/jquery.transit.min.js',\n '/assets/js/vendor/jquery.hoverIntent.js'\n], fetchInject([\n '/assets/js/vendor/jquery.min.js'\n]))))\n```\n\n### Loading and Handling Composite Libraries\n\n**Problem:**\nYou want to deep link to gallery images using [PhotoSwipe](http://photoswipe.com/) without slowing down your page.\n\n**Solution:**\nDownload everything in parallel and instantiate when finished:\n\n```js\nconst container = document.querySelector('.pswp')\nconst items = JSON.parse({{ .Params.gallery.main | jsonify }})\nfetchInject([\n '/css/photoswipe.css',\n '/css/default-skin/default-skin.css',\n '/js/photoswipe.min.js',\n '/js/photoswipe-ui-default.min.js'\n]).then(() => {\n const gallery = new PhotoSwipe(container, PhotoSwipeUI_Default, items)\n gallery.init()\n})\n```\n\nThis 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.\n\n### Suspense\n\n**Problem:** You're experiencing a flash of unstyled content when lazy-loading page resources.\n\n**Solution:** Hide the content until your styles are ready:\n\n```js\nconst pageReady = new Promise((resolve, reject) => {\n document.onreadystatechange = () => {\n document.readyState === \"complete\" && resolve(document);\n };\n});\n\nfetchInject([\n \"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\"],\n pageReady\n).then(() => (document.body.style.visibility = \"visible\"));\n```\n\n## Supported Browsers 🔮\n\nAll browsers with support for [Fetch](http://caniuse.com/#feat=fetch) and [Promises](http://caniuse.com/#search=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.\n\n## Progressive Enhancement 🛟\n\nYou 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.\n\nIn your document `head` get the async loading started right away if the browser supports it:\n\n```js\n(function () {\n if (!window.fetch) return;\n fetchInject([\n '/js/bootstrap.min.js'\n ], fetchInject([\n '/js/jquery.slim.min.js',\n '/js/tether.min.js'\n ]))\n})()\n```\n\nThen, before the close of the document `body` (if JS) or in the `head` (if CSS), provide the traditional experience:\n\n```js\n(function () {\n if (window.fetch) return;\n document.write('<script src=\"/js/bootstrap.min.js\"><\\/script>');\n document.write('<script src=\"/js/jquery.slim.min.jss\"><\\/script>');\n document.write('<script src=\"/js/tether.min.js\"><\\/script>');\n})()\n```\n\nThis is entirely optional, but a good practice unless you're going full hipster.\n\n## Related Projects 🙏🏼\n\n- [fetch](https://github.com/github/fetch) - Polyfill for `window.fetch`\n- [promise-polyfill](https://github.com/taylorhakes/promise-polyfill) - Polyfill for Promises\n- [es-module-loader](https://github.com/ModuleLoader/es-module-loader) - Polyfill for the ES Module Loader\n- [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) - A library for using `fetch` in Node\n- [Dynamic Imports](https://github.com/tc39/proposal-dynamic-import) - `import()` proposal for JavaScript\n- [load-stylesheets](https://github.com/brettz9/load-stylesheets) - Promise-based stylesheet-loading via `<link>` tags\n- [PreloadJS](https://github.com/CreateJS/PreloadJS) - Full-featured JS preloader using XHR2\n- [Gluebert](https://gluebert.com) - Helper for lazy-loading DOM elements using `import()`\n\n## WordPress Plugin 🚀\n\nFetch Inject has been built into a WordPress plugin, enabling Fetch Injection to work within WordPress. [Initial testing](https://hackernoon.com/putting-wordpress-into-hyperdrive-4705450dffc2) shows Fetch Injection enables WordPress to load pages **300% faster** than conventional methods.\n\n![Hyperdrive WordPress Plugin](docs/hyperdrive-logo.webp)\n\nAccess the plugin from the [Hyperdrive repo](https://codeberg.org/vhs/hyperdrive) and see the related [Hacker Noon post](https://hackernoon.com/putting-wordpress-into-hyperdrive-4705450dffc2) for more details.\n\n## Rights ⚖️\n\nFetch Inject - Dynamically inline assets into the DOM using Fetch Injection.<br>\nCopyright (C) 2017-2019, 2022&nbsp;&nbsp;VHS &lt;vhsdev@tutanota.com&gt; (https://vhs.codeberg.page)\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nSee the file COPYING in the source for full license text.\n"
}

@@ -1,37 +0,46 @@

# Fetch Inject
# Fetch Inject
> Dynamically inline assets into the DOM using [Fetch Injection](https://hackcabin.com/post/managing-async-dependencies-javascript/).
[![Latest NPM version](https://flat.badgen.net/npm/v/fetch-inject)](https://npmjs.com/fetch-inject)
[![Weekly downloads](https://flat.badgen.net/npm/dw/fetch-inject)](https://npmjs.com/fetch-inject)
[![Compressed size](https://flat.badgen.net/bundlephobia/minzip/fetch-inject)](https://bundlephobia.com/package/fetch-inject)
[![Hits per month](https://flat.badgen.net/jsdelivr/hits/npm/fetch-inject)](https://www.jsdelivr.com/package/npm/fetch-inject)
[![License](https://flat.badgen.net/npm/license/fetch-inject)](https://codeberg.org/vhs/fetch-inject)
[![Latest NPM version](https://img.shields.io/npm/v/fetch-inject.svg?style=flat-square)](https://www.npmjs.com/package/fetch-inject)
![Zero dependencies](https://img.shields.io/badge/dependencies-0-8892BF.svg?style=flat-square&longCache=true)
![Compressed size](https://img.badgesize.io/https://cdn.jsdelivr.net/npm/fetch-inject@latest?compression=brotli&style=flat-square)
[![NPM downloads per month](https://img.shields.io/npm/dm/fetch-inject.svg?style=flat-square)](https://www.npmjs.com/package/fetch-inject)
[![Hits per month via jsDelivr CDN](https://data.jsdelivr.com/v1/package/npm/fetch-inject/badge)](https://www.jsdelivr.com/package/npm/fetch-inject)
[![License](https://img.shields.io/npm/l/fetch-inject.svg?style=flat-square&longCache=true)](http://www.zlib.net/zlib_license.html)
Dynamically inline assets into the DOM using [Fetch Injection](https://vhs.codeberg.page/post/managing-async-dependencies-javascript/).
Read the [**Hacker News discussion**](https://news.ycombinator.com/item?id=14380191).
## Overview
## Overview 🌱
Fetch Inject implements a Web performance optimization technique known as [Fetch Injection](https://hackcabin.com/post/managing-async-dependencies-javascript/) 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`](https://devdocs.io/dom-fetch/).
Fetch Inject implements a performance optimization technique called [Fetch Injection](https://vhs.codeberg.page/post/managing-async-dependencies-javascript/) 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`](https://devdocs.io/dom-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.
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 [Fetch API](http://devdocs.io/dom/fetch_api) Fetch Inject works alongside [Service Workers](http://devdocs.io/dom-service-workers/) enabling offline-first applications and improving performance in bandwidth-restricted environments.
Because it uses the [Fetch API](http://devdocs.io/dom/fetch_api) Fetch Inject works alongside [Service Workers](http://devdocs.io/dom-service-workers/) for creating offline-first, installable progressive web applications and saves bandwidth on metered networks.
## Playground
## Playground 🛝
Try [CodePen Playground](https://codepen.io/jhabdas/pen/MpVeOE?editors=0012). Reference the [Use Cases](#use-cases) to enhance your understanding of what Fetch Injection can do for you.
Try [CodePen Playground](https://codepen.io/vhsdev/pen/QWOoJqG?editors=0012) while referencing the [Use Cases](#use-cases) provided below.
## Performance
## Performance ⚡️
The following network waterfall diagrams were produced using Fetch Inject to load the WordPress Twenty Seventeen theme for a performance talk [given at](https://habd.as/talks/screaming-fast-wordpress-redis-vultr/) 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.
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.
<p>
<img src="https://git.habd.as/jhabdas/fetch-inject/raw/branch/master/docs/fetch-inject-unprimed-cache.png" title="Fetch Inject Unprimed Cache" width="48%" alt="Screenshot of network waterfall showing parallel resource loading using Fetch Inject">
<img src="https://git.habd.as/jhabdas/fetch-inject/raw/branch/master/docs/fetch-inject-serviceworker-caching.png" width="48%" title="Fetch Inject Service Worker Caching" alt="Screenshot of network waterfall showing parallel resource loading using Fetch Inject with Service Workers">
<img src="docs/fetch-inject-unprimed-cache.webp" title="Fetch Inject Unprimed Cache" width="48%" alt="Screenshot of network waterfall showing parallel resource loading using Fetch Inject">
<img src="docs/fetch-inject-serviceworker-caching.webp" width="48%" title="Fetch Inject Service Worker Caching" alt="Screenshot of network waterfall showing parallel resource loading using Fetch Inject with Service Workers">
</p>
## Syntax
Notice with Service Workers (right) most latency occurs waiting for the initial response.
## Installation 💾
```sh
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] )

@@ -42,4 +51,4 @@

<dl>
<dt>inputs<dd>This defines the resources you wish to fetch. It must be an <code>Array</code> containing elements of type <a target="devdocs" href="http://devdocs.io/dom/usvstring"><code>USVString</code></a> or <a target="devdocs" href="http://devdocs.io/dom/request"><code>Request</code></a>.
<dt>promise<dd><b>Optional.</b> A <a target="devdocs" href="http://devdocs.io/javascript/global_objects/promise"><code>Promise</code></a> to await before injecting fetched resources.
<dt>inputs<dd>Resources to fetch. Must be an <code>Array</code> of type <a target="devdocs" href="http://devdocs.io/dom/usvstring"><code>USVString</code></a> or <a target="devdocs" href="http://devdocs.io/dom/request"><code>Request</code></a> objects.
<dt>promise<dd>Optional. <a target="devdocs" href="http://devdocs.io/javascript/global_objects/promise"><code>Promise</code></a> to await before injecting fetched resources.
</dl>

@@ -61,30 +70,6 @@

## Installing
## Use Cases 🎯
Fetch Inject is available on NPM and CDN. It ships in the following flavors: IIFE, UMD and ES6.
[Use the Playground](#playground) to try any of these on your own.
Save latest minified UMD bundle to a file with [cURL](https://curl.haxx.se/):
curl -o fetch-inject.umd.min.js https://cdn.jsdelivr.net/npm/fetch-inject
Add all three bundles to a [Yarn](https://yarnpkg.com/) package:
yarn add fetch-inject --production
Install the latest `1.7` patch release using [NPM](https://www.npmjs.com/):
npm i -p fetch-inject@~1.7
Download the `1.8.1` ES6 module bundle using [`fetch`](http://devdocs.io/dom/windoworworkerglobalscope/fetch):
```js
fetch('https://cdn.jsdelivr.net/npm/fetch-inject@1.8.1/dist/fetch-inject.es.min.js')
```
For asset pipelines requiring vanilla AMD or CJS modules see the [Development](#development) section.
## Use Cases
Try the [Fetch Inject Playground](#playground) while referencing the following use cases to enhance your understanding of what this library can do for you.
### Preventing Script Blocking

@@ -100,3 +85,3 @@

fetchInject([
'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
'https://cdn.jsdelivr.net/npm/flexsearch/dist/flexsearch.bundle.min.js'
])

@@ -117,3 +102,3 @@ ```

<style>/*! bulma.io v0.4.0 ... */</style>
<script>
<script type="module">
fetchInject([

@@ -246,7 +231,26 @@ '/css/non-critical.css',

## Supported Browsers
### Suspense
**Problem:** You're experiencing a flash of unstyled content when lazy-loading page resources.
**Solution:** Hide the content until your styles are ready:
```js
const pageReady = new Promise((resolve, reject) => {
document.onreadystatechange = () => {
document.readyState === "complete" && resolve(document);
};
});
fetchInject([
"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"],
pageReady
).then(() => (document.body.style.visibility = "visible"));
```
## Supported Browsers 🔮
All browsers with support for [Fetch](http://caniuse.com/#feat=fetch) and [Promises](http://caniuse.com/#search=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
## Progressive Enhancement 🛟

@@ -282,20 +286,4 @@ 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.

## Development
## Related Projects 🙏🏼
1. Clone the repo.
1. Install dev dependencies.
1. Execute `npm run` for a listing of available commands.
If you need vanilla AMD or CJS modules, update `activeConfigs` in `rollup.config.js`.
## Contributing
Please [create a new issue](https://git.habd.as/jhabdas/fetch-inject/issues/new) 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](https://conventionalcommits.org) 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`](http://stackoverflow.com/questions/tagged/fetch-api).
## Related Projects
- [fetch](https://github.com/github/fetch) - Polyfill for `window.fetch`

@@ -308,16 +296,21 @@ - [promise-polyfill](https://github.com/taylorhakes/promise-polyfill) - Polyfill for Promises

- [PreloadJS](https://github.com/CreateJS/PreloadJS) - Full-featured JS preloader using XHR2
- [Gluebert](https://gluebert.com) - A helper for lazy loading DOM elements, StyleSheets and JavaScript files using `import()`
- [Gluebert](https://gluebert.com) - Helper for lazy-loading DOM elements using `import()`
## WordPress Plugin
## WordPress Plugin 🚀
Fetch Inject has been built into a WordPress plugin, enabling Fetch Injection to work within WordPress. [Initial testing](https://hackernoon.com/putting-wordpress-into-hyperdrive-4705450dffc2) shows Fetch Injection enables WordPress to load pages **300% faster** than conventional methods.
![Hyperdrive WordPress Plugin](https://git.habd.as/jhabdas/fetch-inject/raw/branch/master/docs/hyperdrive-logo.png)
![Hyperdrive WordPress Plugin](docs/hyperdrive-logo.webp)
Access the plugin beta from the [Hyperdrive repo](https://git.habd.as/comfusion/hyperdrive) and see the related [Hacker Noon post](https://hackernoon.com/putting-wordpress-into-hyperdrive-4705450dffc2) for more details.
Access the plugin from the [Hyperdrive repo](https://codeberg.org/vhs/hyperdrive) and see the related [Hacker Noon post](https://hackernoon.com/putting-wordpress-into-hyperdrive-4705450dffc2) for more details.
## License
## Rights ⚖️
zlib License
Fetch Inject - Dynamically inline assets into the DOM using Fetch Injection.<br>
Copyright (C) 2017-2019, 2022&nbsp;&nbsp;VHS &lt;vhsdev@tutanota.com&gt; (https://vhs.codeberg.page)
Copyright (C) 2017–2018 Josh Habdas <jhabdas@protonmail.com>
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.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc