我试图通过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
答案 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>