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:
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:
示例代码 [www.CuoXIn.com]
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.
示例代码 [www.CuoXIn.com]
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) }