![](/img/trans.png)
[英]Is there a way to use jQuery functions if they are not defined in the `$(document),ready` function?
[英]Reliable way to use $( document ).ready() in jQuery
假設在頁面生成的中間(例如PHP腳本),您需要在jQuery就緒的情況下附加一些代碼,例如
$( document ).ready(function() {
console.log( "hi!" );
});
問題是,在這一點上, 您不知道jQuery是否已加載 ,如何修改上面的代碼,以便兩種情況都能得到處理?
更新:我問的原因是我想在WordPress博客文章中添加一些JS代碼,但是jQuery加載在頁腳中(我無法更改),因此我想要一種可靠的解決方案,該解決方案在將jQuery加載到瀏覽器中時都可以使用頁眉和頁腳。
如果您僅在文檔就緒內只有console.log()函數:)(我的意思是沒有jQuery)
if(typeof window.jQuery === "undefined") {
window.onload = function () {
console.log("hi!");
}
} else {
jQuery(document).ready(function() {
console.log("hi!");
});
}
其他( UPDATE )
var j = document.createElement('script');
j.type = "text/javascript";
j.url = "url/to/your/jQuery";
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(j, s);
/** then your code */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.