来自谷歌CDN的jquery没有定义

时间:2016-05-29 02:29:41

标签: javascript jquery cdn

我试图通过javascript注入jquery CDN。但是,以下代码似乎没有给我一个错误:" $未定义"。任何帮助将不胜感激!

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

2 个答案:

答案 0 :(得分:2)

  

脚本正在异步加载。

执行onload时,script元素的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')
})




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



o




答案 1 :(得分:0)

试试这个:

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>

OR

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>