动态加载脚本和样式

1,动态加载外部js文件

window.onload=function(){
 alert(typeof BrowserDetect);
}

//这里把代码放到下面是因为必须先有引用代码才可以使用,如果放到window.onlad里面就会出现找不到
var flag=true; //这里需要有一个开关判断什么时候引入
if(flag){
loadScript('browserdetect.js');
}

function loadScript(url){
 var script=document.createELement('script');
 script.type='text/javascript';
 script.src=url;
 document.getElementsByTagNsme('head')[0].appendChild(script);
}

2,动态加载结构里的js内容

var flag=true; 
if(flag){
 var script=document.createELement('script');
 script.type='text/javascript';
//script.appendChild(document.createTextNode("alert('lee')")) //Ie不支持这种写法
 script.text="alert('lee')";
 document.getElementsByTagNsme('head')[0].appendChild(script);
}


 

3,动态样式

var flag=true;
if(flag){
 var link=document.createElement('link');
 link.rel='stylesheet';
 link.type='text/css';
 link.href='basic.css';
 document.getELementsByTagName('head')[0].appendChild('link');
}

4,动态写入页面style

var flag=true;
if(flag){
 var style=document.createElement('style');
 link.type='text/css';
 //style.appendChild(document.createTextNode('#box{width:200px;heght:200px;}')) //ie不支持
 inserRule(document.styleSheets[0],'#box','width:200px;height:200px;')
}

function insertRule(sheet,selectorText,cssText,position){
 //如果是非IE
 if(sheet.insertRule){
  sheet.insertRule(selectorText+"{" + cssText +"}",position);
  //如果是ie
 }else if{
  sheet.addRule(selectorText,cssText,position);
 }
}

猜你喜欢

转载自my.oschina.net/u/1425277/blog/1821022