当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 用JS实现的一个include函数

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 用JS实现的一个include函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 47 ::
收藏到网摘: n/a

很多语言都有类似php中的include和require功能的函数,而唯独javascript没有。
很早就想在js中实现类似的功能,尝试了很多次都没有成功,那天在google上搜索一些关于动态加载css文件的关键词时,发现一个blog(地址找不到了)上的一个为网页的head标签增加link元素的函数,于是就改了一下,写了这个函数。
用法:
include_js(src,[reload]);
src: js文件的路径名
reload:可选参数,0或1,表示是否重复加载同一个url的js文件。
说明:
当包含的js文件中有document.write方法时,在IE下没有反应,但在Mozilla Firefox 下就会让你原来的网页消失,只显示document.write出来的内容:mad:
嘿嘿,对于这个问题,我自然有妙招:
就是重定义 document.write方法,让他不显示任何东西。具体做法:
在 include_js 之前加上这句
document.write = function () { return false;}
这样,就算include过来的js文件含有document.write方法我们也不怕它破坏网页了!:lol::lol:
用途:
本函数可以用于一些广告和统计的js文件异步加载,避免了因加载js文件而造成的网页显示速度慢的问题。
将此函数修改一下便可以动态加载css文件,不过用处就没有加载js文件的大。
复制代码 代码如下:

function include_js(path,reload)
{
var scripts = document.getElementsByTagName("script");
if (!reload)
for (var i=0;i<scripts.length;i++)
if (scripts[i].src && scripts[i].src.toLowerCase() == path.toLowerCase() ) return;
var sobj = document.createElement('script');
sobj.type = "text/javascript";
sobj.src = path;
var headobj = document.getElementsByTagName('head')[0];
headobj.appendChild(sobj);
}