Today, the project needs to use dynamic loading of CSS files. After some hard work, I finally sorted it out. By the way, the function of dynamic loading of JS is integrated into an object, firstCode:
VaR Dynamicloading = { CSS : Function ( Path ) { If (! Path | Path . Length === 0 ) { Throw New Error ( 'Argument "path" is required! ' ); } VaR Head = Document . Getelementsbytagname ( 'Head' )[ 0 ]; VaR Link = Document . Createelement ( 'Link' ); Link . Href = Path ; Link . REL = 'Stylesheet' ; Link . Type = 'Text/CSS' ; Head . Appendchild ( Link ); } , JS : Function ( Path ) { If (! Path | Path . Length === 0 ) { Throw New Error ( 'Argument "path" is required! ' ); } VaR Head = Document . Getelementsbytagname ( 'Head' )[ 0 ]; VaR Script = Document . Createelement ( 'Script' ); Script . SRC = Path ; Script . Type= 'Text/JavaScript' ; Head . Appendchild ( Script ); } }
The object contains two completely independent methods for loading CSS files and JS files. The parameters are the file paths to be loaded. The principle is very simple: create different nodes for different loading file types, add their respective attributes, and finally put them in the head tag. Tested, this method is compatible with various browsers. It is safe, non-toxic, and environmentally friendly. It is actually a constant code for Web developers. Please feel free to use it.
The following is the call code. The exception is simple:
// Dynamically load CSS filesDynamicloading.CSS("Test.css");// Dynamically load JS filesDynamicloading.JS("Test. js");
The demo of this article is also provided here. Download and decompress it. If everything is normal, open the HTML file and the page will pop up a dialog box with bright red, this indicates that it has successfully loaded external CSS and JS files dynamically.
Dynamic_loading.zip
From: http://www.jsmix.com/javascript/dynamic-loading-css-javascript.html