简体   繁体   English

未定义来自Google CDN的jquery

[英]jquery from google CDN is not defined

I am trying to inject jquery CDN by javascript. 我正在尝试通过javascript注入jquery CDN。 The following code, however, does not seem to work giving me an error: "$ is not defined". 但是,以下代码似乎无法正常工作,给我一个错误:“未定义$”。 Any help will be appreciated! 任何帮助将不胜感激!

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. 脚本正在异步加载。

Listen onload event of the script element as script is not really loaded when if-condition is executed. 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!'); } } } 

A generalized function to load scripts asynchronously: 异步加载脚本的通用函数:

 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') }) 

Try this: 尝试这个:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM