簡體   English   中英

如何在JavaScript中有條件地包含腳本文件?

[英]How do I conditionally include a script file in JavaScript?

我想知道是否有辦法在<script></script>標記內有條件地包含腳本文件。

我正在嘗試做這樣的事情:

<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." );
});

但是,我不知道如何使用它。

有沒有辦法做到這一點?

您在$ .getScript的正確軌道上:

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

要使用腳本,請將.getScript回調中的代碼添加到頁面的JavaScript中。 應該在.getScript回調內部包含或調用取決於您要注入的腳本的任何代碼。

在您粘貼的代碼中, console.log語句在注入的腳本加載后運行。 這是一個使用$.getScript加載$.getScript庫並將$.getScript版本記錄到控制台的示例:

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回調中的代碼可以訪問注入腳本中的變量。

暫無
暫無

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

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