2017-04-09 16 views
1

jQueryは外部スクリプトとしてロードされるため、jsファイルにインクルードする必要があります。Uncaught ReferenceError:jQueryがコンソールでも動作していても定義されていません。

はここに私のコードです:

function addjQuery() { 
    if (!window.jQuery) { 
    var jq = document.createElement("script"); 
    jq.type = "text/javascript"; 
    jq.src = "https://code.jquery.com/jquery-3.2.1.min.js"; 
    document.getElementsByTagName("head")[0].appendChild(jq); 
    console.log("Added jQuery!"); 
    } else { 
    console.log("jQuery already exists.") 
    } 
} 
addjQuery(); 

jQuery(function($) { 
    $(document).ready(function() { 
    }); 
}); 

しかし、エラーが発生します。 キャッチされないにReferenceError:私はクロームのdevのツールのコンソールで "jQueryの" または "$" を実行した場合でもjQueryの

が定義されていません、それは働いている。

問題が何ですか?

+4

jQueryの()関数は、前に実行されていますライブラリをロードする – hackerrdave

答えて

1

jQuery()関数はjQueryの前には、スクリプトタグからロードされて発射される - スクリプトがダウンロードが完了したとき、あなたがそれを発射するonloadイベントハンドラを追加することができます。

function addjQuery() { 
    if (!window.jQuery) { 
    var jq = document.createElement("script"); 
    jq.type = "text/javascript"; 
    jq.src = "https://code.jquery.com/jquery-3.2.1.min.js"; 
    document.getElementsByTagName("head")[0].appendChild(jq); 
    jq.onload = initjQuery; 
    console.log("jQuery is loaded!"); 
    } else { 
    console.log("jQuery already exists.") 
    } 
} 

function initjQuery() { 
    jQuery(function($) { 
    $(document).ready(function() { }); 
    }); 
} 

addjQuery(); 
+1

ありがとうございました。それは本当に役に立ちます。 – Softalent

関連する問題