Javascript is powerful, but one problem is that it cannot contain other js files, while other non-scripting languages basically have this function, which is a bit regretful. When you are poor, you want to change. It is increasingly discovered that not dynamically importing files will seriously increase the time of loading the page. After experiments, I found a way to use xhtml to achieve this function. The following function can dynamically import javascript files and css style files. :
function $import(path,type,title){
var s,i;
if(type=="js"){
var ss=document.getElementsByTagName("script");
for(i=0;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 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, they take effect immediately after importing by default. This may cause overlap with the previously selected style effect, causing confusion. So in my blog, I use the following function to implement the style switching function:
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, because the javascript file needs to be loaded remotely, someone may ask whether to execute the statement after $import() immediately after calling the $import() function, or Wait until loading is complete before executing subsequent statements. I did a rough test and found that the subsequent statements are executed after the loading is completed, and if there is code to be executed immediately in the loaded js, it will be executed before the statements following $import(). This is also the result we want, because then we can call the function in the loaded file after $import().
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn