您的位置:首页 > Web前端 > JavaScript

动态载入javascript文件和css样式文件

2008-06-11 00:00 363 查看
下面 两片文章一起看,结合使用效果更好:注意用这个属性setAttribute----javascript功能强大,但一个问题是它不能包含其它的js文件,而其它非脚本语言却基本都是有这个功能的,不得不觉得有点遗憾。穷则思变,越来越发现不动态导入文件会严重加大加载页面的时间,经过实验,发现了一个办法,利用xhtml来实现这个功能,下面的函数就可以动态导入javascript文件和css样式文件:
function $import(path,type,title)...{
var s,i;
if(type=="js")...{
var ss=document.getElementsByTagName("script");
for(i=0;i<ss.length;i++)...{
if(ss[i].src && ss[i].src.indexOf(path)!=-1)return;
}
s=document.createElement("script");
s.type="text/javascript";
s.src=path;
}else if(type=="css")...{
var ls=document.getElementsByTagName("link");
for(i=0;i<ls.length;i++)...{
if(ls[i].href && ls[i].href.indexOf(path)!=-1)return;
}
s=document.createElement("link");
s.rel="alternate stylesheet";
s.type="text/css";
s.href=path;
s.title=title;
s.disabled=false;
}
else return;
var head=document.getElementsByTagName("head")[0];
head.appendChild(s);
}
---------对于样式文件,默认导入后是立即生效的,这有可能会导致和前面一种选定样式效果重叠,造成混乱。所以可以使用下面的函数来实现样式的切换功能:
----------function setStyle(title) ...{
var i, links,eflag=false;
links = document.getElementsByTagName("link");
for(i=0; links[i]; i++) ...{
if(links[i].getAttribute("rel").indexOf("style") != -1 && links[i].getAttribute("title")) ...{
links[i].disabled = true;
if(links[i].getAttribute("title").indexOf(title) != -1)...{links[i].disabled = false;eflag=true;}
}
}
if(!eflag)...{
$import("skin/"+title+"/default.css","css",title);
setStyle(title);
}
}
----------最后,说明一下,因为javascript文件是需要从远程加载的,所以有人可能会问在调用$import()函数后,是立即执行$import()后面的语句,还是等加载完以后再执行其后的语句。粗略试验了一下,发现是等加载完后再执行后面的语句的,而且如果加载的js里有立即执行的代码,那么它会先于$import()后面的语句执行。这也是我们想要的结果,因为这样就可以在$import()之后调用加载的文件里的函数了。
---动态加载外部css或js文件 原理解析:第一步:使用dom创建<script>或者<link>标签,并给他们附加属性,如type等第二步:使用appendChild方法把标签绑定到另一个标签,一般是绑到<head>. 应用:1、提高代码的复用,减少代码量;2、添加一个javascript控制器和 session可以实现动态改变页面样式;3、由于是页面是从上到下依次加载文件的,并且边加载边解释,所以可以添加javascript控制器控制页面文件的加载顺序,如先加载css布局文件,再显示有图片的css美化文件,之后再加载大的falsh文件,或者安内容的重要性来加载。r 阅读提示:e文不好的初学者可以直接看中文,然后拷贝代码试验下。r To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "script" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:
以下为引用的内容:
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //判断文件类型
var fileref=document.createElement('script')//创建标签
fileref.setAttribute("type","text/javascript")//定义属性type的值为text/javascript
fileref.setAttribute("src", filename)//文件的地址
}
else if (filetype=="css"){ //判断文件类型
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
} loadjscssfile("myscript.js", "js") //打开页面时浏览器动态的加载文件
loadjscssfile("javascript.php", "js") // 打开页面时浏览器动态的加载"javascript.php" ,
loadjscssfile("mystyle.css", "css") //打开页面时浏览器动态的加载.css 文件
接下来的工作是绑定到<head>标签。绑定的时候有一个问题就是同一个文件有可能被我们绑定两次,绑定两次浏览器也不会出现异常,但是效率就低了。为了避免r 这种情况我们可以新增一个全局数组变量,把绑定的文件名字保存在里面,每次绑定前先检查一下是否已经存在,如果存在就提示已经存在,如果不存在就绑定。r
document.getElementsByTagName("head")[0].appendChild(fileref)
By referencing the HEAD element of the page first and then calling appendChild(), this means the newly created element is added to the very end of the HEAD tag. Furthermore, you should be aware that no existing element is harmed in the adding of the new element- that is to say, if you call loadjscssfile("myscript.js", "js") twice, you now end up with two new "script" elements both pointing to the same Javascript file. This is problematic only from an efficiency standpoint, as you'll be adding redundant elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is to keep track of the files added by loadjscssfile(), and only load a file if it's new:
var filesadded="" //保存已经绑定文件名字的数组变量
function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("["+filename+"]")==-1){// indexOf判断数组里是否有某一项
loadjscssfile(filename, filetype)
filesadded+="["+filename+"]" //把文件名字添加到filesadded
}
else
alert("file already added!")//如果已经存在就提示
}
checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added
Here I'm just crudely detecting to see if a file that's set to be added already exists within a list of added files' names stored in variable filesadded before deciding whether to proceed or not.
Ok, moving on, sometimes the situation may require that you actually remove or replace an added .js or .css file. Lets see how that's done next.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: