As web developers, we're constantly striving to optimize our website's performance
to provide a seamless user experience. One crucial aspect of this is managing the
loading of third-party JavaScript files, which can significantly impact our
website's Total Blocking Time (TBT). In this blog post, we'll explore how leveraging
requestIdleCallback can help us load third-party JavaScript files more efficiently
and improve our TBT scores.
What is requestIdleCallback?
requestIdleCallback is a JavaScript API that enables developers to schedule tasks
to be executed when the browser's event loop is idle
(Using requestIdleCallback).
This API is particularly useful for non-essential tasks that don't require immediate
attention, such as loading third-party JavaScript files.
The downside is that Safari still doesn't support it, on macOS or iOS, at the time
of writing (Can I use). Our component will
fall back to a short setTimeout when it's missing. If you'd rather have a closer
match to the real thing, there's also a shim.
Why Use requestIdleCallback for Loading Third-Party JavaScript?
Loading third-party JavaScript files can be a significant contributor to TBT,
as it blocks the main thread and prevents the browser from responding to user interactions.
By using requestIdleCallback, we can defer the loading of these files to idle periods,
reducing the impact on our website's responsiveness.
async, defer and requestIdleCallback
async and defer are attributes that can be added to script tags. With both, the
script downloads in parallel with HTML parsing instead of blocking it. They differ in
when the script runs:
asyncruns the script as soon as it finishes downloading, which can be in the middle of parsing, and in any order relative to other scripts.deferwaits until the HTML has finished parsing, then runs scripts in the order they appear, just before theDOMContentLoadedevent.
Either way, the script still runs during page load, when the browser is busiest.
On the other hand, requestIdleCallback is a function that schedules a
callback to be executed during the browser's idle periods. This means that the
callback will be executed when the browser is not busy with other tasks, such as
rendering, parsing, or responding to user input. This approach is useful for tasks
that don't have a specific deadline and can be executed at any time, such as loading
non-essential resources or performing background tasks.
Let's Build a Vue Component To Help
To start, let's build a single file component to load our third-party JavaScript
using requestIdleCallback.
<script>
import { defineComponent, onMounted, onBeforeUnmount } from 'vue';
// Safari doesn't ship requestIdleCallback, so fall back to a short timeout.
const onIdle = (cb, options) => window.requestIdleCallback
? window.requestIdleCallback(cb, options)
: window.setTimeout(cb, 1);
const cancelIdle = (id) => window.cancelIdleCallback
? window.cancelIdleCallback(id)
: window.clearTimeout(id);
export default defineComponent({
name: 'ScriptLoader',
inheritAttrs: false,
props: {
src: {
type: String,
required: true,
},
// Longest wait (ms) for an idle period before loading anyway.
timeout: {
type: Number,
default: 2000,
},
},
emits: ['load', 'error'],
setup(props, { attrs, emit }) {
let idleId = null;
const loadScript = () => {
idleId = null;
const el = document.createElement('script');
// Pass through extra attributes, such as crossorigin or data-*.
for (const [key, value] of Object.entries(attrs)) {
el.setAttribute(key, value);
}
el.addEventListener('load', (e) => emit('load', e));
el.addEventListener('error', (e) => emit('error', e));
el.src = props.src;
document.body.appendChild(el);
};
const scheduleLoad = () => {
idleId = onIdle(loadScript, { timeout: props.timeout });
};
onMounted(() => {
if (document.readyState === 'complete') {
scheduleLoad();
} else {
window.addEventListener('load', scheduleLoad, { once: true });
}
});
onBeforeUnmount(() => {
window.removeEventListener('load', scheduleLoad);
if (idleId !== null) cancelIdle(idleId);
});
// Renderless: nothing to add to the page.
return () => null;
},
});
</script>
This utility component can now be used to load third-party scripts:
<ScriptLoader
src="https://example.com/widget.js"
crossorigin="anonymous"
@load="initWidget"
/>
- It takes a
srcprop that specifies which script to load. - Any other attributes, such as
crossoriginordata-*, are copied onto the script tag. SettinginheritAttrs: falsestops Vue from trying to apply them to the component's own root element, since it doesn't have one. - It emits
loadanderrorevents from the script tag. - Implements lazy loading optimizations:
- If the page is already loaded (
readyState === 'complete'), it usesrequestIdleCallbackto load the script when the browser is idle. - If the page is still loading, it waits for the
loadevent first. - The
timeoutoption sets the longest we'll wait for an idle period. On a page that's always busy, the callback might otherwise never run.
- If the page is already loaded (
- If the component is unmounted before the script is requested, it removes the
loadlistener and cancels the idle callback, so nothing loads for a component that's no longer on the page. - This component is "renderless": its render function returns
null, so it doesn't output any HTML. Without one, Vue logs a "missing template or render function" warning.
Demo
The demo below simulates how different script loading strategies behave during page load. It simulates loading scripts from various CDNs while adding controlled delays to clearly illustrate the timing differences. Watch as regular scripts block execution (red), async scripts load independently (green), defer scripts wait for parsing (blue), and component-loaded scripts wait for browser idle time (orange).
Improvements
Let's improve this a bit, and add a cache so that when multiple components request the same script, it's only added to the page once and every component still gets its load event.
<script>
import { defineComponent, onMounted, onBeforeUnmount } from 'vue';
// src -> Promise for that script's load event, shared by every instance.
const cache = new Map();
// Safari doesn't ship requestIdleCallback, so fall back to a short timeout.
const onIdle = (cb, options) => window.requestIdleCallback
? window.requestIdleCallback(cb, options)
: window.setTimeout(cb, 1);
const cancelIdle = (id) => window.cancelIdleCallback
? window.cancelIdleCallback(id)
: window.clearTimeout(id);
export default defineComponent({
name: 'ScriptLoader',
inheritAttrs: false,
props: {
src: {
type: String,
required: true,
},
// Longest wait (ms) for an idle period before loading anyway.
timeout: {
type: Number,
default: 2000,
},
},
emits: ['load', 'error'],
setup(props, { attrs, emit }) {
let idleId = null;
const injectScript = (src) => new Promise((resolve, reject) => {
const el = document.createElement('script');
// Pass through extra attributes, such as crossorigin or data-*.
for (const [key, value] of Object.entries(attrs)) {
el.setAttribute(key, value);
}
el.addEventListener('load', resolve);
el.addEventListener('error', (e) => {
// Forget the failure so the next request can retry.
cache.delete(src);
el.remove();
reject(e);
});
el.src = src;
document.body.appendChild(el);
});
const loadScript = () => {
idleId = null;
const { src } = props;
if (!cache.has(src)) {
cache.set(src, injectScript(src));
}
cache.get(src).then(
(e) => emit('load', e),
(e) => emit('error', e),
);
};
const scheduleLoad = () => {
idleId = onIdle(loadScript, { timeout: props.timeout });
};
onMounted(() => {
if (document.readyState === 'complete') {
scheduleLoad();
} else {
window.addEventListener('load', scheduleLoad, { once: true });
}
});
onBeforeUnmount(() => {
window.removeEventListener('load', scheduleLoad);
if (idleId !== null) cancelIdle(idleId);
});
// Renderless: nothing to add to the page.
return () => null;
},
});
</script>
The cache is a module-level Map, shared by every instance of the component, that stores a Promise for each script's load event, keyed by URL. The first request for a URL adds the script tag and stores its Promise. Later requests for the same URL skip straight to waiting on that Promise, so each external script is only loaded once no matter how many components request it, and every one of them still gets load (or error).
If a script fails to load, we remove its tag and delete it from the cache, so the next component that asks for it gets a fresh attempt instead of the stored failure.
What This Does and Doesn't Fix
It's worth being clear about what's actually improving. requestIdleCallback doesn't make a script any cheaper to run. If a widget takes 300ms of main-thread work, it still takes 300ms. What changes is when that work happens.
Lighthouse measures TBT in a window during page load, so moving the work after load and into idle time takes it out of that window, and the score improves. That's a real improvement for users too, since the page becomes usable sooner. But if someone clicks or types while the deferred script is running, they'll still wait for it, and that shows up in Interaction to Next Paint (INP) rather than TBT. So check both metrics, and check real-user data as well as Lighthouse.
This approach fits scripts that aren't needed to use the page: chat widgets, analytics, social embeds. It doesn't fit scripts the page depends on to work.
If you're using Nuxt, you may not need to build this at all. Nuxt Scripts provides a useScript composable that loads third-party scripts on a trigger you choose, including when the app is idle after hydration. Writing a component like this is still a good way to understand what those tools do for you.
Conclusion
By implementing this script loader component, we gain better control over how and when external scripts load in our Vue applications. This leads to improved performance, better user experience, and cleaner code organization.
Remember, performance optimization is an ongoing process, and this component is just one tool in our optimization toolkit. Always measure and monitor your application's performance to ensure your optimizations are having the desired impact.