开发者

Waiting on JS class load from dynamic script loading

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].append开发者_运维百科Child(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.


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜