Sample Code for dynamically loading and removing js/css files and css sample code
This article briefly introduces how to dynamically load, remove, and replace js/css files. Sometimes, when we write the front-end, there will be a need to dynamically load some East such as css js, which can reduce the load burden on users and thus improve the response efficiency. The following code is provided.
<Script language = "JavaScript"> // dynamically load a js/css file 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>
Example:
Loadjscssfile ("myscript. js "," js ") loadjscssfile (" javascript. PHP "," js ") loadjscssfile (" mystyle.css "," css ") <scriptlanguage =" javascript "> // move the loaded js/cssfunction 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>
Example:
removejscssfile("somescript.js","js")removejscssfile("somestyle.css","css")
Summary
The above is a sample code for dynamic loading and removal of js/css files. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!