Skip to Content

loadJS()

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

JavaScript July 2, 2019

Usage

JavaScript
nebula.loadJS(url, callback)

Parameters

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

callback
(Optional) (Function) A function to run after the JS resource has been loaded
Default: None

Request or provide clarification »

Additional Notes

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

Source File

Located in /assets/js/nebula.js on line 2963.

Note: This function contains 1 to-do comment.

JavaScript
nebula.loadJS = function(url, callback){
    //@todo "Nebula" 0: listen for requestIdleCallback after IE11 no longer supported (still need conditional per Safari): https://caniuse.com/#feat=requestidlecallback
    if ( typeof url === 'string' ){
        var lazyScriptElement = document.createElement('script'); //Create a script element
        lazyScriptElement.src = url; //Set the script src to the URL

        //Callback when element has loaded
        if ( callback ){
            lazyScriptElement.onload = callback;
        }

        //Track exceptions
        lazyScriptElement.onerror = function(){
            ga('send', 'exception', {'exDescription': '(JS) ' + url + ' could not be loaded', 'exFatal': false});
            nebula.nv('event', 'JavaScript resource could not be dynamically loaded');
        };

        document.body.appendChild(lazyScriptElement); //Add the new script to the DOM
    } else {
        console.error('nebula.loadJS() requires a valid URL.');
    }
};

Override

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

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