Skip to Content

workbox()

Functionality for registering and communicating to the Nebula service worker.

JavaScript February 8, 2021

Usage

This function runs automatically, so it is not called manually. Is this incorrect?

Demo


Waiting for JavaScript to load...

Additional Notes

To install the Nebula Service Worker, find the sw.js file in the Nebula Child resources directory and move it to the root directory. Then, enable Service Worker in Nebula Options.

If you need to override the name and/or location of the file, override the sw_location() function (documentation here).

When using an SSL, Nebula sets a Content Security Policy (CSP) header to upgrade all http protocol requests to https.

Source File

Located in /assets/js/modules/optimization.js on line 145.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.workbox = async function(){
    jQuery('.nebula-sw-install-button').addClass('inactive'); //If manually placing this button, start with this inactive class to prevent CLS

    if ( nebula.site?.options?.sw ){ //If Service Worker is enabled in Nebula Options
        if ( 'serviceWorker' in navigator ){ //If Service Worker is supported (Firefox 44+, Chrome 45+, Edge 17+, Safari 12+)
            //When debugging unregister SW and clear caches
            if ( nebula.site?.options?.bypass_cache || nebula.get('debug') || nebula.get('audit') || nebula.dom.html.hasClass('debug') ){
                nebula.unregisterServiceWorker(); //Unregister the ServiceWorker
                nebula.emptyCaches(); //Clear the caches
                return false;
            }

            window.performance.mark('(Nebula) SW Registration [Start]');

            //Dynamically import Workbox-Window
            import('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-window.prod.mjs').then(async function(module){
                const Workbox = module.Workbox;
                const workbox = new Workbox(nebula.site.sw_url);

                //Listen for Service Worker installation (this is different than PWA installation)
                workbox.addEventListener('installed', function(event){
                    //Skip waiting
                    workbox.messageSkipWaiting(); //Will probably end up using this, but try it without it first– it was not in the tutorial

                    if ( !event.isUpdate ){
                        //Service worker installed for the first time
                    }
                });

                //Activate the service worker
                workbox.addEventListener('activated', async function(event){
                    //Send the Workbox service worker router a list of resources to cache
                    workbox.messageSW({
                        type: 'CACHE_URLS', //This message type is handled in Workbox
                        payload: {
                            urlsToCache: [
                                location.href, //Current page
                                ...performance.getEntriesByType('resource').map(function(resource){ //Get all of the resources used by this page
                                    return resource.name;
                                }),
                            ]
                        },
                    });

                    //Now we can send messages back and forth
                    nebula.dom.document.trigger('nebula_workbox_active', workbox); //Allow others to interactive with Workbox (Ex: send messages with workbox.messageSW)
                    //const swVersion = await workbox.messageSW({type: 'GET_VERSION'}); //The message type here must match what the SW expects

                    //event.isUpdate will be true if another version of the service worker was controlling the page when this version was registered. It will be false on the very first installation
                    if ( !event.isUpdate ){
                        //If your service worker is configured to precache assets, those assets should all be available now.
                        nebula.dom.document.trigger('nebula_sw_first_activation');
                    }
                });

                //When the service worker begins controlling
                workbox.addEventListener('controlling', function(event){
                    //Service worker is now controlling
                });

                //Waiting to activate the new service worker until all tabs running the current version have fully unloaded
                workbox.addEventListener('waiting', function(event){
                    //A new service worker has installed, but it cannot activate until all tabs running the current version have fully unloaded.
                    //Create an update button to reload the page
                    jQuery('<button id="nebula-sw-update"><i class="fas fa-fw fa-sync-alt"></i> Update available. Click to reload.</button>').appendTo('body').on('click', function(){
                        window.location.reload();
                        nebula.animate('#nebula-sw-update', 'nebula-zoom-out');
                        return false;
                    });

                    //Show the button
                    //window.requestIdleCallback(function(){ //when Safari supports requestIdleCallback
                        window.requestAnimationFrame(function(){
                            //jQuery('#nebula-sw-update').addClass('active'); //Not showing to users as of Feb 2021. Need to make sure this reload method works (and with multiple tabs)
                        });
                    //});
                });

                //If the service worker becomes redundant
                workbox.addEventListener('redundant', function(event){
                    ga('send', 'exception', {'exDescription': '(JS) The installed service worker became redundant.', 'exFatal': false});
                });

                //Notify the user of cache updates (this is from documentation, so test this thoroughly)
                workbox.addEventListener('message', function(event){
                    if ( event.data.type === 'CACHE_UPDATED' ){
                        const updatedURL = event.data.payload;
                    }

                    nebula.dom.document.trigger('nebula_sw_message', event.data);
                });

                //Register the service worker after above workbox event listeners have been added
                workbox.register().then(function(){
                    window.performance.mark('(Nebula) SW Registration [End]');
                    window.performance.measure('(Nebula) SW Registration', '(Nebula) SW Registration [Start]', '(Nebula) SW Registration [End]');
                }).catch(function(error){
                    ga('send', 'exception', {'exDescription': '(JS) ServiceWorker registration failed: ' + error, 'exFatal': false});
                });
            });

            nebula.pwa();
        }
    } else {
        nebula.unregisterServiceWorker();
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.workbox = function(){
    //Write your own code here, leave it blank, or return false.
}