Load jQuery Library Dynamically using javascript

Load jQuery Library Dynamically using javascript

Added by Mind Hunter updated on Monday, November 20, 2017

jQuery Loaded | !Loaded:

First of all, we will test the presence of jQuery library, following is function to test jQuery is already loaded or not.

function IsLoaded(){
	if(typeof jQuery == 'undefined'){
		return false;
	}
	return true;
}
				

There are different methods to test if jQuery is loaded or not, some of them are given below.

if (window.jQuery) {  
	// jQuery is loaded          
}
else{
	// jQuery not loaded        
}				
				
if (typeof window.jQuery == 'undefined') {
    // jQuery not loaded
} else {
    // jQuery loaded
}				
				
if (jQuery) {
	// jQuery loaded
} else {
	// jQuery not loaded
}				
				

Loading jQuery

Our first task is completed. Now it’s time to load jQuery at runtime.

(function() {    
    var jscript = document.createElement("script");
    jscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
    jscript.type = 'text/javascript';
	jscript.async = true;
    jscript.onload = function() {
        var $ = window.jQuery;        
    };
    document.getElementsByTagName("head")[0].appendChild(jscript);
})();				
				

What if we need to call some function when library loaded for that we are going to make function rather Anonymous function.

function LoadLibrary(liburl,callback){
	var jscript = document.createElement("script");
	jscript.type = 'text/javascript';
	jscript.src = liburl;
	//for IE type browsers
	if (jscript.readyState) { 
    	jscript.onreadystatechange = function () {
        	if (jscript.readyState == "loaded" || jscript.readyState == "complete") {
            	jscript.onreadystatechange = null;
                callback();
            }
        };
	} else {
		jscript.onload = function () {
			callback();
        };
    }
	document.getElementsByTagName("head")[0].appendChild(jscript);
}
				

Useage of above function is simple.

LoadLibrary('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
	function(){
		alert('loaded');
	}
);				
				

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected