- Javascript dynamically inserts CSS styles into HTML
- Javascript dynamic insert in HTMLCode
The dynamic insertion mentioned above is not a file that introduces .css or. js.
1. dynamically insert CSS code Function Loadstylebystring (CSS ){
VaR Style = Document. createelement ("style ");
Style. type = "text/CSS ";
Try {
// When running in Firefox, safrai, chrome, and opera, an error is reported in IE. ie regards <style> as a special node similar to <SCRIPT>, access to its subnodes is not allowed. In fact, the error thrown by IE is the same as the error thrown when a subnode is added to the <SCRIPT> element. The solution to this problem in IE is to access the stylesheet attribute of the element, which has another csstext attribute and can accept CSS code.
Style. appendchild (document. createtextnode (CSS ));
} Catch (Ex ){
// IE series,
Style.stylesheet.css text = CSS;
}
VaR Head = Document. getelementsbytagname ("head") [0];
Head. appendchild (style );
2. dynamically insert JavaScript code
FunctionLoadscriptbystring (SCRIPT ){
VaR G = Document. createelement ('script ');
VaR S = Document. getelementsbytagname ('head') [0];
G. Text = script;
S. parentnode. insertbefore (G, S );
}
Some frequently-used code that has been compiled by myself for so long (not written by myself), I feel quite helpful. I am going to get a web debugging tool. I don't need to install any plug-ins for Javascript, Firefox, chrome, which has very powerful debugging Functions
Attaches a dynamic JS, CSS file in the code
Call Method
JS-Minisite. jsloader. Load ('xx. js', function () {alert ('js loaded complete ')});
CSS-Minisite.cssloader('xx.css ');
Minisite = New Object ();
Minisite. browser = {
IE:/MSIE/. Test (window. Navigator. useragent. tolowercase ()),
Moz:/Gecko/. Test (window. Navigator. useragent. tolowercase ()),
Opera:/Opera/. Test (window. Navigator. useragent. tolowercase ()),
Safari:/Safari/. Test (window. Navigator. useragent. tolowercase ())
};
Minisite. jsloader = {
Load: Function (Surl, fcallback ){
VaR _ Script = Document. createelement ("script ");
VaR Charbt = "UTF-8 ";
If (Arguments [2]) {
Charbt = arguments [2]
}
_ Script. setattribute ("charset", charbt );
_ Script. setattribute ("type", "text/JavaScript ");
_ Script. setattribute ("src", Surl );
Document. getelementsbytagname ("head") [0]. appendchild (_ script );
If (Minisite. browser. ie ){
_ Script. onreadystatechange = Function (){
If ( This . Readystate = "loaded" | This . Readystate = "complete "){
Fcallback ();
}
};
} Else If (Minisite. browser. Moz ){
_ Script. onload = Function (){
Fcallback ();
};
} Else {
Fcallback ();
}
}
};
Minisite. cssloader =Function(Surl ){
VaR_ CSS = Document. createelement ("Link ");
_ CSS. setattribute ("rel", "stylesheet ");
_ CSS. setattribute ("charset", "UTF-8 ");
_ CSS. setattribute ("type", "text/CSS ");
_ CSS. setattribute ("href", Surl );
Document. getelementsbytagname ("head") [0]. appendchild (_ CSS );
};