April 30, 2012
Jquery is Ready wrapper
Question by Mahan
is there any javascript code wrap that can be use to wait for Jquery to load and create a callback after loading jquery successfully?
something like this
JqueryWait(function(){
//my magnificent jquery codes ^^
});
I want a code wrap something like this…
Explanation:
I’m using headjs and i loaded jquery in a separate code of headjs. now my other scripts relies on the jquery and that’s why that other script must know if the jquery is already loaded. I know about the callback function of headjs but my other script can’t be put on the callback function
Answer by qwertymk
Try this:
function JqueryWait(fn) {
if (jQuery) fn();
else setTimeout(function() { JqueryWait(fn); }, 100);
}
JqueryWait(function(){
//my magnificent jquery codes ^^
});
Answer by Starx
You dont need extra function to do this. jQuery’s $(document).ready(function() { });
is enough for this.
$(function() {
//ever code written inside here is run, after the jQuery & DOM is ready
});
Anways, there is another way to do check if jQuery has been loaded or not
if (typeof jQuery == 'undefined') {
//... jquery not loaded
}