TIL loading third-party scripts onto service workers
POSTED ON:
TAGS: serviceworker javascript cache optimization
Web.Dev had a killer guide on how to load third-party scripts in a way to optimize page performance here: Loading Third-Party JavaScript and Efficiently load third-party JavaScript
There's the usual tips like Resource Hints, async/defer, self-hosting, and lazy load.
But the one I was really interested in was using Service workers!
An alternative to self-hosting scripts would be using Service Workers to cache them. This can give you greater control over how often they are re-fetched from the network. This could also be used to create a loading strategy where requests for non-essential third parties are throttled until the page reaches a key user moment.
Example code looks like this:
// your main JS file
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
} else {
// Fallback to loading scripts normally
var jqueryScript = document.createElement('script');
jqueryScript.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
document.head.appendChild(jqueryScript);
var bootstrapLink = document.createElement('link');
bootstrapLink.rel = 'stylesheet';
bootstrapLink.href = 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
document.head.appendChild(bootstrapLink);
}
// sw.js - your service worker file
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('my-cache').then(function(cache) {
return cache.addAll([
'https://code.jquery.com/jquery-3.6.0.min.js',
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'
]);
})
);
});
If the serviceWorker exists, then it loads the sw.js
file.
Related TILs
Tagged: serviceworker