![](/img/trans.png)
[英]How do I include a remote javascript file in a Greasemonkey script?
[英]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.