javascript包含javascript檔案 先給出直接封裝好的兩個js
function include_js(path)
{
var sobj = document.createElement('script');
sobj.type = "text/javascript";
sobj.src = path;
var headobj = document.getElementsByTagName('head')[0];
headobj.appendChild(sobj);
}
function include_css(path)
var fileref=document.createElement("link")
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.href = path;
include_css("css/kefu.css");
include_js("HashMap.js");
include_js("WebComm.js");
-----------------------------
document.write("<scr"+"ipt language=javascript src='zdz.js'></scr"+"ipt>");
這樣就可以了!中國站長的統計裡面就有這個代碼!
document.write("<link href=/"css/WebComm.css/" rel=/"stylesheet/" type=/"text/css/" />");
用document.write方法無法放到頭檔案那裡,有時候會有加載先後順序的問題。用include可以。
第二種方法是用字元串的形式
file1.js:
var file2 = '<script language="javascript" src="file2.js"><//script>';
document.write(file2);
第三種方法使用include
//直接包含js檔案。
function include_abc(path)
//根據已經包含的第一個js檔案路徑,包含新的js檔案
function include(path)
{
var scripts = document.getElementsByTagName("script");
if(!scripts) return;
var jsPath = scripts[0].src;
jsPath=jsPath.substring(0,jsPath.lastIndexOf('/')+1);
sobj.src = jsPath+path;
例如:
現在已經有一Common.js檔案包含在aspx頁面上,路徑是src="/JScript/Common.js"
如果用include包含: include("WebsiteConfig.js");将把WebsiteConfig.js包含進頁面,路徑和Common.js相同。
如果用include_abc包含則需要全路徑,include_abc("/JScript/WebsiteConfig.js");
使用include,必須要求頁面上已經有一個包含的js檔案.
使用include_abc則不需要任何條見,就可以包含,但是必須指定要包含的js檔案路徑。