[英]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.