Skip to Content

prefetch()

Prefetch a URL with a resource hint.

JavaScript February 7, 2021

Usage

JavaScript
nebula.prefetch(url, callback)

Parameters

url
(Required) (String) The URL to prefetch
Default: None

callback
(Optional) (Function) A function to run when the URL has been prefetched successfully
Default: None

element
(Optional) (Object) A jQuery object of the element
Default: This is used for contextual references

Parameter Notes

The callback function will only run if the prefetch was successful.

The element expects a jQuery object and uses it to check for context (things like the “download” attribute) to further determine if this should be prefetched.

Request or provide clarification »

Additional Notes

This function will not prefetch resources for users on 2G connections or if the “Save Data” option is enabled.

Source File

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

1 Hook

Find these filters and actions in the source code below to hook into them. Use wp.hooks.doAction() and wp.hooks.addFilter() in your JavaScript file.

Filters
"nebulaPrefetchBlocklist"
Need a new filter hook? Request one here.

Actions
This function has no action hooks available. Request one?

JavaScript
nebula.prefetch = async function(url = '', callback, element){
    if ( url && url.length > 1 && url.indexOf('#') !== 0 && typeof window.requestIdleCallback === 'function' ){ //If the URL exists, is longer than 1 character and does not begin with # (waiting for Safari to support requestIdleCallback)
        //If network connection is 2G don't prefetch
        if ( navigator.connection?.effectiveType.toString().includes('2g') ){ //'slow-2g', '2g', '3g', or '4g'
            return false;
        }

        //If Save Data is supported and Save Data is requested don't prefetch
        if ( navigator.connection?.saveData ){
            return false;
        }

        //Ignore request to prefetch the current page
        if ( url === window.location.href || url === nebula.post?.permalink ){
            return false;
        }

        //Ignore links with certain attributes and classes (if the element itself was passed by reference)
        if ( element && (jQuery(element).is('[download]') || jQuery(element).hasClass('no-prefetch') || jQuery(element).parents('.no-prefetch').length) ){
            return false;
        }

        //Only https protocol (ignore "mailto", "tel", etc.)
        if ( !url.startsWith('https') ){
            return false;
        }

        //Ignore certain files
        if ( /\.(?:pdf|docx?|xlsx?|pptx?|zipx?|rar|tar|txt|rtf|ics|vcard)/.test(url) ){
            return false;
        }

        //Strip out unnecessary parts of the URL
        url = url.split('#')[0]; //Remove hashes

        //Ignore blocklisted terms (logout, 1-click purchase buttons, etc.)
        let prefetchBlocklist = wp.hooks.applyFilters('nebulaPrefetchBlocklist', ['logout', 'wp-admin']);

        jQuery.each(prefetchBlocklist, function(index, value){
            if ( url.includes(value) ){
                url = ''; //Empty the URL so it will fail the next condition
                return false; //This just breaks out of the loop (does not stop the function)
            }
        });

        window.requestIdleCallback(function(){ //Wait until the browser is idle before prefetching
            if ( url.length && !jQuery('link[rel="prefetch"][href="' + url + '"]').length ){ //If prefetch link for this URL has not yet been added to the DOM
                jQuery('<link rel="prefetch" href="' + url + '">').on('load', callback).appendTo('head'); //Append a prefetch link element for this URL to the DOM
            }
        });
    }
};

Override

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

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