2

For reasons that are beyond my control I have to load jQuery via a dynamically appended <script> tag, and only do this upon some arbitrary event, not at page load.

My problem is in detecting the moment when jquery is ready, for the code below doesn't work:

(function(){
    var s=document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
    document.getElementsByTagName('head')[0].appendChild(s);
})()

$(document).ready(function() {
  // something that uses jquery and currently doesn't work
});

How do I detect the moment when jquery is ready to be used in this particular configuration?

Thanks in advance

3

3 Answers 3

2

Use the onload and onreadystatechange event handlers:

var scr   = document.createElement('script'),
    head      = document.getElementsByTagName('head')[0];

scr.onload = scr.onreadystatechange = function(){
        if( scr.readyState ){
            if(scr.readyState === 'complete' || scr.readyState === 'loaded'){
                scr.onreadystatechange = null;                                                  
                myReadyFunc();
            }
        } 
        else{                               
                myReadyFunc();          
        }
};  

head.insertBefore(scr, head.firstChild);

function myReadyFunc() {
    $(document).ready(function() {
      // something that uses jquery and currently doesn't work
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

An old-school answer :) You can create a recursive polling function that check to see if the $ object exists eg:

function poller(){
    if($.length != 0){
       //do what you want

    }else{
       setTimeout(poller, 100);
    }    
}

And right after you load the jQuery script run the poller function.

Comments

1

You can handle the <script> element's onreadystatechange event, and, if this.readyState is complete or loaded, run your function.
For Firefox, handle the onload event.

You can expose this in a wrapper function which takes a function as a parameter, and calls it if jQuery has been loaded, or puts it in an array (to call in the load handler) if it's not loaded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.