2010-11-19 87 views
1

這是一個非常簡單的腳本,應該加載jQuery。我可以在jQuery是加載Firebug的腳本選項卡看到,但我得到「當我嘗試使用$沒有定義」的錯誤。誰能幫我明白了什麼是錯的?在Javascript(js)文件中加載jQuery

//function to add scripts 
function include(file) 
{ 
    var script = document.createElement('script'); 
    script.src = file; 
    script.type = 'text/javascript'; 
    script.defer = true;  
    document.getElementsByTagName('head').item(0).appendChild(script); 
} 
//add jQuery 
include('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); 

//See if jQuery is working 
$(document).ready(function() { 
    $('#internal').show(); 
}) 

//////////// 
//RETURNS: "$ is not defined $(document).ready(function() {" 

奇怪的是,如果唐「T嘗試使用jQuery在這同一個腳本,而不是我加載使用jQuery的另一個js文件它的工作

//function to add scripts 
function include(file) 
{ 
    var script = document.createElement('script'); 
    script.src = file; 
    script.type = 'text/javascript'; 
    script.defer = true;  
    document.getElementsByTagName('head').item(0).appendChild(script); 
} 
//add jQuery 
include('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); 

//add my custom script that wants to use jQuery 
include('scripts/testScript.js') 

testScript.js

$(document).ready(function() { 
    $('#external').show(); 
}) 

我很欣賞這個任何建議。

回答

5

我猜這是因爲瀏覽器將只執行完成執行當前文件後添加的腳本節點中的JavaScript。

瀏覽器將在一個線程中執行當前腳本。當它到達腳本的末尾時,它會執行DOM中的下一個腳本。它不能停止通過一個腳本運行以跳到下一個腳本。

您可能想看看Google的JavaScript loader。工作的方式是,你告訴它加載一個外部的js文件,並註冊一個回調,以便在加載該文件時執行。

你可以用回調來做,因爲回調中的代碼只有在瀏覽器完成當前文件的執行並轉移到下一個文件後才能執行。你的不能讓做的事情是讓瀏覽器從一個js文件切換到另一個(即當它首次執行文件內容時)。

+0

+1 - 你需要使用該腳本的' onload'處理程序來觸發回調。 – user113716 2010-11-19 18:13:19

0

當你像你一樣動態添加一個腳本文件時,該文件不會被執行,直到你的javascript的其餘部分被執行;因此在示例中,一個jQuery源被壓低到jQuery代碼下面,因此返回undefined。

原因代碼示例兩個作品是因爲您有兩個動態添加的文件,並將它們按順序添加到底部,所以執行jQuery源代碼,然後執行您的jQuery代碼。

0

所以,通過使用JavaScript來加載jQuery,你是異步加載文件。你的代碼將開始加載jQuery,然後繼續調用你的document.ready代碼,這將失敗,因爲jQuery尚未完成加載或開始執行。

當你使用兩個include時,它會加載每個文件,等到第二個文件被執行時,第一個文件已經被執行,這就是它的工作原理。

您確實需要設置一個回調函數,以便一旦jQuery完成加載,它將執行文檔就緒任務以及運行任何需要jQuery的其他代碼。

1

正如其他答案中所解釋的,jquery是異步加載的,因此在調用$(document).ready()時,jquery是net加載的。

function include(file){ 
    var script = document.createElement('script'); 
    script.src = file; 
    script.type = 'text/javascript'; 
    script.defer = true; 
    script.onload= function(){ 
     $(document).ready(function() { 
     //your code here 
     }) 
    } 
    document.getElementsByTagName('head').item(0).appendChild(script); 
} 
//add jQuery 
include('https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); 

看看這裏的一個例子::您可以通過添加自己的代碼,腳本元素的onload事件處理避免這種 http://jsfiddle.net/CrReF/