Skip to Content

predictiveCacheListeners()

Attempt to predict the next pageview for caching/prefetching.

JavaScript July 2, 2019

Usage

JavaScript
nebula.predictiveCacheListeners()

Parameters

This function does not accept any parameters. Is this incorrect?

Additional Notes

If a service worker is being used (and Cache API is available), the resource will be fetched and added to the cache. Otherwise, it will attempt to prefetch with a resource hint instead.

It also does not run when offline.

Note: This only enables event listeners! To add to the cache, see nebulaAddToCache() ornebulaPrefetch().

Source File

Located in /assets/js/nebula.js on line 274.

JavaScript
nebula.predictiveCacheListeners = function(){
    //Any post listing page
    if ( jQuery('.first-post .entry-title a').length ){
        nebula.prefetch(jQuery('.first-post .entry-title a').attr('href'));
    }

    //Internal link hovers
    var predictiveHoverTimeout;
    jQuery('a').on('mouseenter', function(){
        var oThis = jQuery(this);
        var url = oThis.attr('href');

        if ( url && !predictiveHoverTimeout ){
            predictiveHoverTimeout = window.setTimeout(function(){
                predictiveHoverTimeout = null; //Reset the timer
                nebula.prefetch(url); //Attempt to prefetch
            }, 250);
        }
    }, function(){
        if ( predictiveHoverTimeout ){
            window.clearTimeout(predictiveHoverTimeout);
            predictiveHoverTimeout = null;
        }
    });

    //Once idle, prefetch the top-level nav items and buttons
    if ( typeof window.requestIdleCallback === 'function' ){
        //Prefetch certain elements on window idle
        window.requestIdleCallback(function(){
            //Top-level primary nav links
            jQuery('ul#menu-primary > li.menu-item > a').each(function(){
                nebula.prefetch(jQuery(this).attr('href'), false, jQuery(this));
            });

            //First 5 buttons
            jQuery('a.btn, a.wp-block-button__link').slice(0, 4).each(function(){
                nebula.prefetch(jQuery(this).attr('href'), false, jQuery(this));
            });
        });
    }
};

Override

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

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