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?
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 });
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.
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 };
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With