![](/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.