JavaScript is powerful, but a problem is that it can not contain other JS files, and other non-scripting languages are basically have this function, have to feel a little regret. Shang, increasingly found that not dynamic import files will significantly increase the time to load the page, after the experiment, found a way to use XHTML to achieve this function, the following function can dynamically import JavaScript files and CSS style files:
Copy Code code as follows:
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);
}
For style files, the default import takes effect immediately, which can cause confusion by overlapping with the previous selected style effect. So in my blog, I use the following functions to implement the switching function of the style:
Copy Code code as follows:
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);
}
}
Finally, let's say that because JavaScript files need to be loaded remotely, one might ask whether the statement following $import () is executed immediately after the $import () function is invoked, or after the load is finished, followed by subsequent statements. I have a rough test, I found that after loading and then execute the following statement, and if the loaded JS has immediately executed code, then it will precede the $import () followed by the statement execution. This is also the result we want, because we can call the function in the loaded file after $import ().