jquery 来自 google CDN 未定义

jquery from google CDN is not defined

我正在尝试通过 javascript 注入 jquery CDN。但是,以下代码似乎不起作用,给我一个错误:“$ is not defined”。任何帮助将不胜感激!

var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript')
var jqui = document.createElement('script')
jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
jqui.setAttribute('type', 'text/javascript')
document.head.appendChild(jqry)
document.head.appendChild(jqui)

if (typeof jQuery == 'undefined') {
    alert('no jquery')
}

$... // codes using jquery

Scripts are being loaded asynchronously.

侦听 script 元素的 onload 事件,因为 script 在执行 if-condition 时并未真正加载。

var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript');
document.head.appendChild(jqry)

jqry.onload = function() {
  if (typeof jQuery == 'undefined') {
    alert('no jquery')
  } else {
    alert('Loaded!');
    var jqui = document.createElement('script');
    jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
    jqui.setAttribute('type', 'text/javascript');
    document.head.appendChild(jqui);
    jqui.onload = function() {
      alert('jquery-ui Loaded!');
    }
  }
}

异步加载脚本的通用函数:

function loadScript(src, callback) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  document.head.appendChild(script);
  script.onload = callback || function() {};
}
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js', function() {
  alert('jQuery Loaded!');
  loadScript('//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
})

试试这个:

var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src","https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
<head></head>

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js";
document.head.appendChild(script);
<head></head>