2

I have a JS script which depends on jQuery.

I want to check for jQuery, and if it is not loaded/available add it myself, wait for it to load, and then define my script class.

The code I currently use:

// load jQuery if not loaded yet
if (typeof (jQuery) == 'undefined') {
  var fileref = document.createElement('script');
  fileref.setAttribute("type", "text/javascript");
  fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.4.4.min.js');
  document.getElementsByTagName('body')[0].appendChild(fileref);

  (ready = function() {
    if ( typeof (jQuery) == 'undefined' || !jQuery) {
      return setTimeout( ready, 1 );
    } else {
      // jQuery loaded and ready
      jQuery.noConflict();
    }
  })();
}

// … class definition follows
var MView = function() …

Now, with FireFox 4 (I think it did work before, or execution was just too slow), it will continue the scripts execution even when I still want to wait on jQuery. The recursive setTimeout is non-blocking.

How can I fix this? Make setTimeout blocking? Use another approach? Is there a better way? A way at all?

The class should be global scope, so it can be used on the page that includes this script file.

2

1 Answer 1

7

I would recommend 2 things.

  1. Use 'if (!jQuery)' since undefined is considered falsey
  2. Use the script tag's onload event

if (!window.jQuery) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.4.4.min.js');
    fileref.onload = function() {
        // Callback code here
    };
    document.getElementsByTagName('body')[0].appendChild(fileref);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Even if I define my class as window.class there then, I will not be able to use it on the page, as that won’t wait on load.
Try putting your class definition into a function, and invoke that function after jQuery is loaded.
Was playing stupid games with setTimeout and onload event is what I needed. Thank you!

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.