等待动态脚本加载的JS类加载 [英] Waiting on JS class load from dynamic script loading

查看:70
本文介绍了等待动态脚本加载的JS类加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个依赖于jQuery的JS脚本。

I have a JS script which depends on jQuery.

我想检查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.

我目前使用的代码:

// 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() …

现在,使用FireFox 4(我认为它之前有效,或执行速度太慢),即使我还想等待jQuery,它仍会继续执行脚本。递归的setTimeout是非阻塞的。

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.

我该如何解决这个问题?使setTimeout阻塞?使用另一种方法?有没有更好的办法?一种方式?

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. 使用'if(!jQuery) )'因为undefined被认为是假的

  2. 使用脚本标签的onload事件




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

这篇关于等待动态脚本加载的JS类加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆