Skip to Content

prefetch()

Prefetch a URL with a resource hint.

JavaScript May 18, 2020

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/nebula.js on line 323.

Note: This function contains 4 to-do comments.

JavaScript
nebula.prefetch = 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 #
        //If network connection is 2G don't prefetch
        if ( nebula.has(navigator, 'connection.effectiveType') && navigator.connection.effectiveType.toString().indexOf('2g') >= 0 ){ //'slow-2g', '2g', '3g', or '4g' //@todo "Nebula" 0: Replace with optional chaining
            return false;
        }

        //If Save Data is supported and Save Data is requested don't prefetch
        if ( nebula.has(navigator, 'connection.saveData') ){ //@todo "Nebula" 0: Replace with optional chaining
            if ( navigator.connection.saveData ){ //@todo "Nebula" 0: Use optional chaining
                return false;
            }
        }

        //Ignore request to prefetch the current page
        if ( url === window.location.href ){ //Add || url === nebula?.post?.permalink when optional chaining can be used
            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 ( !/^https/.test(url) ){ //Change this to .startsWith() when we use ES6
            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.)
        var prefetchBlocklist = ['logout'];

        //@todo "Nebula" 0: Allow other JS to add to the blocklist here... https://core.trac.wordpress.org/changeset/41375

        jQuery.each(prefetchBlocklist, function(index, value){
            if ( url.indexOf(value) != -1 ){
                return false;
            }
        });

        window.requestIdleCallback(function(){ //Wait until the browser is idle before prefetching
            if ( !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.
}