Skip to Content
Menu

loadJS()

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

JavaScript June 17, 2022

Usage

JavaScript
nebula.loadJS(url, handle)

Parameters

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

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

Callback
(Optional) (Function) A function to run after the JS resource has loaded
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 (using the promise)

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

Run a function after the JS has loaded (using the callback)

JavaScript
nebula.loadJS('https://example.com/file.js', 'example-file', 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');
});

Listen for Bootstrap JS to be available using a promise

JavaScript
//Use this to listen for that Promise to resolve
nebula.site.resources.lazy.promises['bootstrap.bundle.min.js'].then(function(){
    console.log('Bootstrap JS is now available');
});

Listen for Bootstrap JS using a standard event listener

JavaScript
//Note that if this event listener is called *after* the resource is loaded, it will never trigger! So wrap it in a condition to check if it is already available!
if ( typeof bootstrap === 'object' ){ //If bootstrap is not already loaded
    console.log('Bootstrap JS is already available'); //Call your function here
} else {
    jQuery(document).on('nebula_loadjs', function(handle){
        if ( handle == 'bootstrap.bundle.min.js' ){
            console.log('Bootstrap JS is now available'); //Call your function here
        }
    });
    
    // ----or----

    //Use the specific trigger without needing the handle conditional.
    jQuery(document).on('nebula_loadjs_bootstrapbundleminjs', function(){
        console.log('Bootstrap JS is now available'); //Call your function here
    });
}

Additional Notes

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

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/optimization.js on line 611.

    No Hooks

    This function does not have any filters or actions available. Request one?
    JavaScript
    nebula.loadJS = async function(url, handle, callback=false){
        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
            }
    
            //Look into import() here instead of generating a <script> element to append. The import() function does work with third-party endpoints.
    
            //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);
            }).then(function(){
                //Trigger an event if that is an option to listen for as well
                nebula.dom.document.trigger('nebula_loadjs_' + handle.replaceAll(/[^a-zA-Z]/gi, '')); //This one is specific to the handle being loaded. Ex: 'nebula_loadjs_bootstrapbundleminjs'
                nebula.dom.document.trigger('nebula_loadjs', handle); //This one is a generic one that passes the handle name
    
                if ( callback ){ //Callback just in case it is preferred instead of the returned promise.
                    return callback(); //Should this have a return on it? That would break the promise, but if a callback is specified it would be expected...
                }
            });
    
            return nebula.site.resources.lazy.promises[handle];
        }
    
        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. 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.loadJS = function(url, handle, Callback){
        //Write your own code here, leave it blank, or return false.
    }


    For dynamically imported module function overrides:

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