转载自:http://blog.csdn.net/erlian1992/article/details/50413710
先来一贯使用的HTML文档代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > < html xmlns = "http://www.w3.org/1999/xhtml" > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=gb2312" /> < title > DOM </ title > < script type = "text/javascript" > window.onload = function (){ } </ script > </ head > < body > < div id = "box" class = "box1 box2 box3" > div区域 </ div > </ body >
一动态加载外部JS文件
要动态加载外部index.js文件的代码:
动态加载外部JS文件的代码:
var flag= true ; if (flag){ loadScript("index.js" ); }; function loadScript(url){ var script=document.createElement( "script" ); script.type="text/javascript" ; script.src=url; document.getElementsByTagName("head" )[0].appendChild(script); };
加载前的效果:
加载后的效果:
二动态加载JS代码
var flag= true ; if (flag){ var script=document.createElement( "script" ); script.type="text/javascript" ; script.text ="alert('I am JS code!')" ; document.getElementsByTagName("head" )[0].appendChild(script); };
加载前的效果:
加载后的效果:
三动态加载外部CSS样式文件
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); };
添加前的效果:
添加后的效果:
四动态加载CSS样式
var flag= true ; 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){ if (sheet.insertRule){ sheet.insertRule(selectorText+"{" +cssText+ "}" ,position); } else if (sheet.addRule){ sheet.addRule(selectorText,cssText,position) } };
添加前的效果:
添加后的效果: