Easy to learn JavaScript 26: How to dynamically add JS scripts and CSS styles in DOM programming Learning
The following HTML document code is used:
<Script type = "text/javascript"> window. onload = function () {}</script> div Region
1. dynamically load external JS files
Code for dynamically loading the external index. js file:
alert("I am JS file!");
Code for dynamically loading external JS files:
// Dynamically load the external JS file var flag = true; // set true and then load if (flag) {loadScript ("index. js "); // loaded external JS file}; function loadScript (url) {var script = document. createElement ("script"); script. type = "text/javascript"; script. src = url; document. getElementsByTagName ("head") [0]. appendChild (script );};
Effect before loading:
Effect after loading:
2. dynamically load JS Code
// Dynamically load JS Code var flag = true; // set true and then load if (flag) {var script = document. createElement ("script"); script. type = "text/javascript"; script. text = "alert ('I am JS code! ') "; Document. getElementsByTagName (" head ") [0]. appendChild (script );};
Effect before loading:
Effect after loading:
3. dynamically load external CSS style files
Var flag = true; // if (flag) {loadCss ("style.css") ;}; function loadCss (url) {var link = document. createElement ("link"); link. type = "text/css"; link. rel = "stylesheet"; link. href = url; document. getElementsByTagName ("head") [0]. appendChild (link );};
Effect before adding:
Effect after adding:
4. dynamically load CSS styles
// Dynamically load the CSS style var flag = true; // set true and then load if (flag) {var style = document. createElement ("style"); style. type = "text/css"; document. getElementsByTagName ("head") [0]. appendChild (style); var sheet = document. styleSheets [0]; insertRule (sheet ,". box1 "," color: red ", 0) ;}; // function insertRule (sheet, selectorText, cssText, position) {// determine if (sheet. insertRule) {sheet. insertRule (selectorText + "{" + cssText + "}", position);} // determines whether it is an IE browser else if (sheet. addRule) {sheet. addRule (selectorText, cssText, position )}};
Effect before adding:
Effect after adding: