簡體   English   中英

未定義來自Google CDN的jquery

[英]jquery from google CDN is not defined

我正在嘗試通過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

腳本正在異步加載。

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

嘗試這個:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM