Skip to Content

loadJS()

Dynamically load JavaScript resources after the page has already been rendered.

JavaScript February 21, 2021

Usage

JavaScript
nebula.loadJS(url, handle)

Parameters

url
(Required) (String) The URL of the JS resource to load
Default: None

handle
(Required) (String) The name to identify this resource
Default: None

Parameter Notes

This function returns a Promise which are also available in the object nebula.site.resources.lazy.promises.

Request or provide clarification »

Examples

Simply lazy load a JS resource

JavaScript
nebula.loadJS('https://example.com/file.js', 'example-file');

Call a function after the resource is loaded

JavaScript
nebula.loadJS('https://example.com/file.js', 'example-file').then(function(){
    console.log('file.js is now available');
});

Listen for a specific Promise

JavaScript
//In this example, this line happens somewhere else:
nebula.loadJS('https://example.com/file.js', 'example-file');

//Use this to listen for that Promise to resolve
nebula.site.resources.lazy.promises['example-file'].then(function(){
    console.log('file.js is now available');
});

Additional Notes

Unlike jQuery getScript(), this function caches the JavaScript resource.

Source File

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

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.loadJS = async function(url, handle){
    nebula.site.resources.lazy.promises = nebula.site.resources.lazy.promises || {}; //Ensure this exists

    //Listen for requestIdleCallback when Safari supports it
    if ( typeof url === 'string' ){
        if ( !handle ){
            handle = url.split('\\').pop().split('/').pop().split('?')[0]; //Get the filename from the URL and remove query strings
        }

        //Store the promise so it can be listened for elsewhere if necessary
        nebula.site.resources.lazy.promises[handle] = new Promise(function(resolve, reject){
            var lazyScriptElement = document.createElement('script');
            lazyScriptElement.src = url;
            lazyScriptElement.onload = resolve;
            lazyScriptElement.onerror = reject;

            document.body.appendChild(lazyScriptElement);
        });

        return nebula.site.resources.lazy.promises[handle];
    } else {
        nebula.help('nebula.loadJS() requires a valid URL. The requested URL is invalid: ' + url, '/functions/loadjs/');
    }
};

Override

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

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