Skip to Content
Menu

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.

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

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

    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://cdn.jsdelivr.net/npm/[email protected]/build/workbox-window.prod.mjs').then(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 if 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="fa-solid 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){
                        gtag('event', 'exception', {
                            message: '(JS) The installed service worker became redundant.',
                            fatal: 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){
                        gtag('event', 'exception', {
                            message: '(JS) ServiceWorker registration failed: ' + error,
                            fatal: false
                        });
                    });
                });
    
                nebula.pwa();
            }
        } else {
            nebula.unregisterServiceWorker();
        }
    };
    

    Override

    To override or disable this JavaScript function, simply redeclare it with the exact same function name. Remember: Some functionality is conditionally loaded via dynamic imports, so if your function is not overriding properly, try listening for a DOM event (described below).

    JavaScript

    For non-module import functions:

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


    For dynamically imported module function overrides:

    jQuery(window).on('load', function(){
        nebula.workbox = function(){
            //Write your own code here, leave it blank, or return false.
        }
    });


    Custom Nebula DOM events do also exist, so you could also try the following if the Window Load listener does not work:

    jQuery(document).on('nebula_module_loaded', function(module){
        //Note that the module variable is also available to know which module specifically was imported
        if ( typeof nebula.workbox === 'function' ){
            nebula.workbox = function(){
                //Write your own code here, leave it blank, or return false.
            }
    	}
    });