Skip to main content

A cross browser JavaScript function to dynamically load a JavaScript into the DOM with an optional callback parameter.

'use strict';

/**
 * Load JavaScript
 *
 * @param {String} url The URL or path to JavaScript file.
 * @param {Function} Optional callback function invoked after loading.
 * @return {Element} The created script element.
 */
function loadScript(url, callback) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.charset = 'utf-8';

    if (callback && typeof callback === 'function') {
        script.onload = script.onreadystatechange = function () {
            var state = this.readyState;
            if (!state || (/loaded|complete/).test(state)) {
                script.onload = script.onreadystatechange = null;
                callback();
            }
        };
    }

    script.src = url;
    document.body.appendChild(script);

    return script;
}

//=============================================================================
//
// Example Usage
//
// jQuery CDN versions
// -------------------
//
// - //code.jquery.com/jquery-latest.min.js
// - //ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
// - //ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
//
//=============================================================================

loadScript('//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function () {
    if (typeof jQuery === 'undefined') {
        throw new Error('Error occured while attempting to load jQuery.');
    }

    jQuery.noConflict();

    var jQueryVersion = jQuery.fn.jquery.split(' ')[0];
    console.log('jQuery v%s loaded.', jQueryVersion);
});