Saturday, February 1, 2014

Load jQuery If Not Loaded

The following script loads the jQuery from specified source if jQuery is not already loaded on page.

You need to call the function ensurejQuery with parameter of source jQuery to used.
Example:

ensurejQuery('http://code.jquery.com/jquery-1.11.0.min.js');


The complete code:

function ensurejQuery(src) {
    if (typeof window['jQuery'] == 'undefined') {

        // if HTML5 url
        if (src.substring(0, 2) === '//') {
            writeScriptTag(src);
            return;
        }

        // If this page is requested as secure ('https://') 
        // use same for script source
        if (location.protocol === "https:" && src.substring(0, 6) !== 'https:') {
            var httpsUrl = src.replace('http://','https://')
            writeScriptTag(httpsUrl);
            return;
        }

        writeScriptTag(src);
    }
    function writeScriptTag(jslocation) {
        document.write('<scr' + 'ipt type="text/javascript" src="' + jslocation + '"></sc' + 'ript>');
    }

}

// Example:
// ensurejQuery('http://code.jquery.com/jquery-1.11.0.min.js');







No comments: