不能动态加载jquery, bootstrap, D3.js, knockout.js的CDN

Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery

本文关键字:js knockout CDN D3 bootstrap 动态 加载 jquery 不能 不能动      更新时间:2023-09-26

不能动态加载jquery、bootstrap、D3.js、knockout.js的CDN。当checkjquery()为false时,我使用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加载时间。onload触发器会比timeout更好,但是下面是你的代码。

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

您也可以看看这种方法