Home >Web Front-end >JS Tutorial >Sample code for dynamically loading and removing js/css files
This article briefly introduces the sample code for dynamically loading, removing, and replacing js/css files. The code is simple and easy to understand, very good, and has reference loading. Friends who need it can refer to it.
This article briefly introduces the dynamic Load, remove, and replace js/css files. Sometimes when we are writing the front-end, there will be a need to dynamically load some things such as css js. This can reduce the user's loading burden and improve response efficiency. The code is posted below.
<script language="JavaScript"> //动态加载一个js/css文件 function loadjscssfile(filename, filetype){ if (filetype=="js"){ varfileref=document.createElement('script') fileref.setAttribute("type","text/javascript") fileref.setAttribute("src",filename) } else if (filetype=="css"){ varfileref=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) } </script>
Usage example:
loadjscssfile("myscript.js","js") loadjscssfile("javascript.PHP","js") loadjscssfile("mystyle.css","css") <scriptlanguage="javascript"> //移动已经加载过的js/css function removejscssfile(filename,filetype){ vartargetelement=(filetype=="js")? "script" :(filetype=="css")? "link" : "none" var targetattr=(filetype=="js")?"src" : (filetype=="css")? "href" :"none" varallsuspects=document.getElementsByTagName(targetelement) for (var i=allsuspects.length; i>=0;i--){ if (allsuspects[i] &&allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1) allsuspects[i].parentNode.removeChild(allsuspects[i]) } } </script>
Usage example:
removejscssfile("somescript.js","js") removejscssfile("somestyle.css","css")
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Uploading files through Ajax Using FormData for Ajax requests
jQuery Ajax method for uploading files
Use ajax to implement asynchronous refresh request
##
The above is the detailed content of Sample code for dynamically loading and removing js/css files. For more information, please follow other related articles on the PHP Chinese website!