Load jQuery if not loaded (Asynchronous Way)

If you load scripts through ajax and they won’t execute.

<script>
// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

    if (typeof $ == 'function') {
        // warning, global var
        thisPageUsingOtherJSLibrary = true;
    }
    
    function getScript(url, success) {
        var script     = document.createElement('script');
        script.src = url;       
        var head = document.getElementsByTagName('head')[0],
        done = false;       
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function() {        
            if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {          
            done = true;                
                // callback function provided as param
                success();              
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);               
            };      
        };      
        head.appendChild(script);   
    };
    
    getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', function() {
    
        if (typeof jQuery=='undefined') {       
            // Super failsafe - still somehow failed...     
        } else {        
            // jQuery loaded! Make sure to use .noConflict just in case
            
            // HERE IS THE CODE WE WANT TO EXECUTE ASYNC
            $.getScript( "js/calculations_reg.js", function( data, textStatus, jqxhr ) {
              // console.log( data ); // Data returned
              // console.log( textStatus ); // Success
              // console.log( jqxhr.status ); // 200
              // console.log( "Load was performed." );
            });
            //nik fancyCode();          
            //nik if (thisPageUsingOtherJSLibrary) {
                // Run your jQuery Code
            //nik } else {
                // Use .noConflict(), then run your jQuery Code
            //nik }     
        }   
    }); 
} else { // jQuery was already loaded
    // Run your jQuery Code
};
</script>

After that place your code that you want to run.

Leave a Reply

Your email address will not be published. Required fields are marked *