2014-07-21 104 views
0

我想知道是否有條件地在<script></script>標籤中包含腳本文件。如何有條件地在JavaScript中包含腳本文件?

我試圖做這樣的事情:

<script> 
if(condition) 
{ 
    <script src="/hts/functions.js"></script> //include this file if condition is met 
} 
</script> 

我發現這個代碼:

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) { 
    console.log(data); // Data returned 
    console.log(textStatus); // Success 
    console.log(jqxhr.status); // 200 
    console.log("Load was performed."); 
}); 

不過,我不知道如何使用它。

有沒有辦法做到這一點?

+0

你使用jQuery嗎? – Andy

+0

如果「if」與Internet Explorer有關,那麼你可以使用條件語句,否則,你可能只是「借用」Google,facebook等用於腳本的異步加載代碼,並將它放在條件。 – adeneo

回答

1

你是正確的軌道$ .getScript上:

if(someConditionIsTrue){ 
    // load script from the server 
    $.getScript("somePath/onTheServer/script.js", function(data, textStatus, jqxhr) { 
     // do something after the load is complete 
    }); 
} 
1

要使用的腳本,在.getScript回調的代碼添加到您的JavaScript的網頁。任何依賴於注入腳本的代碼都應該包含在內,或者在.getScript回調中調用。

在您粘貼的代碼中,console.log語句在注入腳本加載後運行。下面是使用$.getScript加載Underscore.js庫和日誌下劃線的文本控制檯的例子:

var condition=true; 
var pathToScript='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js'; 
if(condition){ 
    // load script from the server 
    $.getScript(pathToScript, function(data, textStatus, jqxhr) { 
     console.log(_.VERSION); 
    }); 
}; 

的jsfiddle:http://jsfiddle.net/WA4f4/2/

我稍微修改您的代碼,所以它會在的jsfiddle和工作證明getScript回調中的代碼可以訪問注入腳本中的變量。

相關問題