Javascript is powerful, but one problem is that it cannot contain other JS files, while other non-scripting languages basically have this function, so I have to feel a bit sorry. When the problem is getting worse, it is increasingly found that non-dynamic File Import will seriously increase the page loading time. After experiment, we found a way to use XHTML to implement this function, the following functions can dynamically import JavaScript files and CSS style files:
CopyCode The Code is 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 );
}
Style files take effect immediately after being imported by default. This may cause overlapping effects with the previous selected style, resulting in confusion. In my blog, we use the following function to implement style switching:
Copy code The Code is 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 explain that because JavaScript files need to be loaded remotely, some people may ask that after the $ import () function is called, the statement following $ import () is executed immediately, or execute the following statement after loading. After a rough test, I found that the statement is executed after loading. If the loaded JS contains the code that is executed immediately, it will run before $ import () the following statement is executed. This is what we want, because we can call the function in the loaded file after $ import.