[英]Is There Any Way To Include a Javascript File Inside Another JS File?
我尝试了在网站上其他问题中找到的3条建议,但似乎没有一条对我有用,我不确定为什么。
// #1
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.getElementsByTagName('head')[0].appendChild(imported);
// #2
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
// #3
document.write( '<script language="javascript" src="myotherscript.js" />' );
我尝试包含的文件基本上是一个大型文件,其变量声明如下:
var agent = [
"csv",
"drawfile",
"excel",
"flash",
"hangul",
"html",
"image",
"msword",
"ooxml",
"pdf",
"ppt",
"txt",
"wmf"];
关于什么可能导致问题的任何想法?
更新
只是说我要包含的JS文件是从数据库动态生成的更新,因此请避免使用正则表达式不断添加和删除相同的代码,因为我将其存储在一个单独的文件中。
变量conconend用于将值填充到动态下拉列表中,因此,不起作用意味着在下拉列表中没有值:(
如果唯一的目的是包括另一个javascript文件,以在全局范围内声明一堆变量及其值,为什么不只是在<script type="text/javascript" src="myotherscript.js"></script>
在您的其他脚本源包含之前html文档的头?
编辑:
问题是您不能从方法内部定义全局变量。 您确实有可能将整个脚本文件(或至少受影响的部分)封装在jQuery ajax函数中,该函数首先评估包含的文件。 这将使您包含的变量处于正确的范围内。 这就是我的意思
$.ajax({
url: 'path/to/included/file',
success: function(msg) {
eval(msg); // This is where your included variables are in regard to scope
// This is where you would paste all of your dependent functions and whatnot
}
});
// Outside of the ajax method, you won't be able to use your included properties
我现在将使用require插件 ,我认为jquery将在下一个核心版本1.6中使用
var getScript = function(jsPath) {
$.ajax({
dataType:'script',
async:false,
cache:true,
url:jsPath
});
};
http://requirejs.org/是此类问题中最受欢迎的
谢谢大家的帮助,但我认为导致错误的原因是一些需要在变量内转义的字符。
马丁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.