【问题标题】:Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery无法使用jquery动态加载jquery、bootstrap、D3.js、knockout.js的CDN
【发布时间】:2015-08-05 23:54:56
【问题描述】:

无法使用jquery动态加载jquery、bootstrap、D3.js、knockout.js的CDN。当 checkjquery() 为假时,我使用 jquerycdn 变量传递给 loadscript()。但是当我通过仍然没有加载 jquery CDN 时。其余文件(如 bootstrap、D3.js、knockout.js 等)面临同样的问题。所有这些文件 CDN 都保存在一个 js 文件中。

请检查以下代码:-

this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"

Initialize.prototype.checkJQuery = function () {
    if (window.jQuery) {
        return true;
    } else {
        return false;
    }
};

if (!this.checkJQuery ()) {
                console.log("jquerynot available")               
                this.loadJQuery ();
                if (!this.checkJQuery ()) {
                    throw "Error loading jquery"
                }
            } else {
                console.log("jquery available")
            }

Initialize.prototype.loadJQuery = function () {
//    var js_code = atob(this.jqueryStr);
//    eval(js_code);
    this.loadScript(this.jqueryCDN);
};

Initialize.prototype.loadScript = function (src) {
    var my_awesome_script = document.createElement('script');
    my_awesome_script.setAttribute('src', src);
    document.head.appendChild(my_awesome_script);
}

【问题讨论】:

  • 您的浏览器控制台是否出现任何错误?
  • $ 未定义。{这意味着我猜 jquery 未加载}。
  • 您是否尝试过在 HTML 中而不是在 JS 中添加 jQuery 的 CDN?

标签: javascript jquery cdn


【解决方案1】:

在检查它是否已加载之前,您需要给 jQuery 加载时间。 onload 触发器会比超时更好,但这是您的代码工作。

function Initialize() {
  var self = this;
  this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
  if (!this.checkJQuery()) {
    console.log("jquery not available")
    this.loadJQuery();
    setTimeout(function() {
      if (!self.checkJQuery()) {
        throw "Error loading jquery"
      } else {
        alert("jQuery loaded!");
      }
    }, 2500);
  } else {
    console.log("jquery available")
  }
}
Initialize.prototype.checkJQuery = function() {
  if (window.jQuery) {
    return true;
  } else {
    return false;
  }
};


Initialize.prototype.loadJQuery = function() {
  //    var js_code = atob(this.jqueryStr);
  //    eval(js_code);
  this.loadScript(this.jqueryCDN);
};

Initialize.prototype.loadScript = function(src) {
  var my_awesome_script = document.createElement('script');
  my_awesome_script.setAttribute('src', src);
  document.body.appendChild(my_awesome_script);
}

var i = new Initialize();

你也可以看看this approach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多