Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load jQuery if it is not already loaded?

I have a initializor.js that contains the following:

if(typeof jQuery=='undefined') {     var headTag = document.getElementsByTagName("head")[0];     var jqTag = document.createElement('script');     jqTag.type = 'text/javascript';     jqTag.src = 'jquery.js';     headTag.appendChild(jqTag); } 

I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.

However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:

"jQuery is undefined".

Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!

Also, can I dynamically add code into the $(document).ready() event? Or wouldn't it be necessary just to add some Click events to a few elements?

like image 723
Jeff Avatar asked Jul 25 '11 07:07

Jeff


People also ask

How do I ensure jQuery is loaded?

In general, you just use the following basic "document loaded" test in jquery. Straight from the beginners jquery tutorial: $(document). ready(function() { // do stuff when DOM is ready });

How do I check if jQuery is already loaded?

You can just type window. jQuery in Console . If it return a function(e,n) ... Then it is confirmed that the jquery is loaded and working successfully.

How do I make sure JavaScript is loaded?

What is the best way to make sure javascript is running when page is fully loaded? If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.: window. onload = function() { // Everything has loaded, so put your code here };


1 Answers

jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.

e.g.

function myJQueryCode() {     //Do stuff with jQuery }  if(typeof jQuery=='undefined') {     var headTag = document.getElementsByTagName("head")[0];     var jqTag = document.createElement('script');     jqTag.type = 'text/javascript';     jqTag.src = 'jquery.js';     jqTag.onload = myJQueryCode;     headTag.appendChild(jqTag); } else {      myJQueryCode(); } 
like image 198
Adam Heath Avatar answered Oct 01 '22 04:10

Adam Heath