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
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!