Skip to Content
Menu

fetch()

A wrapper for the JavaScript Fetch API that simplifies the pattern for basic calls.

JavaScript September 18, 2024

Usage

JavaScript
nebula.fetch(url, headers, type).then(function(data){...})

Parameters

url
(Required) (String) The endpoint URL for the data to be fetched
Default: None

headers
(Optional) (Object) Optional fetch headers
Default: None

type
(Optional) (String) The expected data type for processing (json or text)
Default: json

data
(Required) (Mixed) The fetched data response
Default: None

Parameter Notes

If no headers are needed, you can pass the type as the second parameter.

Request or provide clarification »

Examples

Simple JSON fetch

JavaScript
nebula.fetch('https://example.com/data.json').then(function(json){
    console.log('here is the fetched json:', json);
});

A text fetch with no-cache headers

JavaScript
nebula.fetch('https://example.com/data.txt', {
    cache: 'no-cache'
}, 'text').then(function(data){
    console.log('here is the fetched text data:', data);
});

Fetching text data without passing a headers object

JavaScript
nebula.fetch('https://example.com/data.txt', 'text').then(function(data){
    console.log('here is the fetched text data:', data);
});

Catch errors

JavaScript
nebula.fetch('https://example.com/data.json').then(function(json){
    console.log('here is the fetched json:', json);
}).catch(function(error) {
    console.log('Fetch error:', error);
});

Demo


Check the Network, Console, and/or Performance tabs in DevTools to see demo results.

Additional Notes

For more complicated patterns, you may want to use the Fetch API directly, but this Nebula function simplifies the traditional fetch() pattern significantly for simple tasks.

This Nebula fetch function will also automatically monitor performance using marks and measures. So when running tests in the Performance tab of DevTools or using WebPageTest (for example), you’ll see each of the individual fetch timings appear in the associated track. This allows for scrutinizing which endpoints may be slowing down the website.

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/utilities.js on line 296.

    No Hooks

    This function does not have any filters or actions available. Request one?
    JavaScript
    nebula.fetch = async function(url = false, headers = {}, type = 'json') {
        if ( !url ){
            nebula.help('nebula.fetch() requires a URL to retrieve.', '/functions/fetch/');
            return false;
        }
    
        if ( typeof headers !== 'object' ){ //If the type is passed as the second parameter
            type = headers;
            headers = {};
        }
    
        const fetchLabel = nebula.sanitize(url);
        window.performance.mark('(Nebula) Fetch Start ' + fetchLabel);
    
        await nebula.yield();
    
        //Create a new promise to handle fetch
        let fetchPromise = new Promise(async function(resolve, reject){
            try {
                let response = await fetch(url, headers);
    
                if ( !response.ok ){
                    throw new Error('Network response was not ok: ' + response.statusText);
                }
    
                let data;
                if ( type === 'json' ){
                    data = await response.json();
                } else {
                    data = await response.text();
                }
    
                window.performance.mark('(Nebula) Fetch End ' + fetchLabel);
                window.performance.measure('(Nebula) Fetch ' + url, '(Nebula) Fetch Start ' + fetchLabel, '(Nebula) Fetch End ' + fetchLabel);
    
                resolve(data);
            } catch(error){
                reject(error);
            }
        });
    
        return fetchPromise;
    };
    

    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.fetch = function(url, headers, type, data){
        //Write your own code here, leave it blank, or return false.
    }


    For dynamically imported module function overrides:

    jQuery(window).on('load', function(){
        nebula.fetch = function(url, headers, type, data){
            //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.fetch === 'function' ){
            nebula.fetch = function(url, headers, type, data){
                //Write your own code here, leave it blank, or return false.
            }
    	}
    });