Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
fetch-inject
Advanced tools
A fetching async loader and DOM injection sequencer for high-performance websites.
This library implements a performance optimization technique known as Fetch Injection for managing async dependencies with JavaScript. It also works for stylesheets too, and was designed to be extensible for any resource type which can be loaded using fetch
.
Use Fetch Inject to dynamically import page resources such as JS and CSS in parallel (even across the network), and load them into your page in a desired sequence.
Because it uses Fetch API, Fetch Inject will work alongside Service Workers, enabling you take the performance of your Progressive Web Apps to an entirely new level.
Here's an example waterfall using Fetch Inject to loading the WordPress Twenty Seventeen theme over 4G with an unprimed browser cache.
Click the image for a live demo of the application used to produce the above waterfall.
Promise<Array<Object>> fetchInject(inputs[, promise])
Array
containing elements of type USVString
or Request
.
Promise
to await before injecting fetched resources.
A Promise
that resolves to an Array
of Object
s. 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 ... */"
}]
Try Fetch Inject on CodePen using the latest version available on CDN.
Reference the Use Cases to get a feel for what it can do.
Fetch Inject is available on NPM, Bower and CDN. It ships in the following flavors: IIFE, UMD and ES6.
npm i -p fetch-inject
bower i -p fetch-inject
To grab the latest UMD bundle from CDN:
curl -o fetch-inject.umd.min.js https://cdn.jsdelivr.net/npm/fetch-inject
See the Development section for asset pipelines requiring vanilla AMD or CJS modules.
Problem: External scripts can lead to jank or SPOF if not handled correctly.
Solution: Load external scripts without blocking:
fetchInject([
'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
])
This is a simple case to get you started. Don't worry, it gets better.
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>
fetchInject([
'/css/non-critical.css',
'https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css'
])
</script>
Unlike loadCSS
, Fetch Inject is smaller, doesn't use callbacks and ships a minifed UMD build for interop with CommonJS.
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) => {
fetchInject([
'https://cdn.jsdelivr.net/smooth-scroll/10.2.1/smooth-scroll.min.js'
])
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.
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...
fetchInject([
'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})
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([
'https://npmcdn.com/bootstrap@4.0.0-alpha.5/dist/js/bootstrap.min.js'
], fetchInject([
'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
'https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js'
]))
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 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...
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 = [
'https://cdn.jsdelivr.net/tooltip/1.2.0/tooltip.min.js',
'https://cdn.jsdelivr.net/tooltip/1.2.0/tooltip-theme-arrows.css'
]
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([
'/assets/js/main.js'
], fetchInject([
'/assets/js/vendor/superfish.min.js'
], fetchInject([
'/assets/js/vendor/jquery.transit.min.js',
'/assets/js/vendor/jquery.hoverIntent.js'
], fetchInject([
'/assets/js/vendor/jquery.min.js'
]))))
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 }})
fetchInject([
'/css/photoswipe.css',
'/css/default-skin/default-skin.css',
'/js/photoswipe.min.js',
'/js/photoswipe-ui-default.min.js'
]).then(() => {
const gallery = new PhotoSwipe(container, PhotoSwipeUI_Default, items)
gallery.init()
})
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.
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.
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([
'/js/bootstrap.min.js'
], fetchInject([
'/js/jquery.slim.min.js',
'/js/tether.min.js'
]))
})()
Then, before the close of the document body
, provide the traditional experience to avoid blocking the parser until content is visible:
(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.
npm run
for a listing of available commands.If you need vanilla AMD or CJS modules, update activeConfigs
in rollup.config.js
.
Please use Issues for bugs and enhancement requests only. Bug reports not accompanied by a reduced test case, sufficient backing research and information to help progress the library may be closed without explanation.
When submitting pull requests, use npm run commit
to create Commitizen-friendly commit messages. Pulls should be squashed into a single commit prior to review and should PR against a backing issue.
If you need support, you know where to go.
window.fetch
fetch
in Nodeimport()
proposal for JavaScriptFetch 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.
Access the plugin beta Hyperdrive repo on GitHub and see the related Hacker Noon article for more details.
FAQs
Dynamically inline assets into the DOM using Fetch Injection.
The npm package fetch-inject receives a total of 480 weekly downloads. As such, fetch-inject popularity was classified as not popular.
We found that fetch-inject demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.