動態加載腳本和樣式

1,動態加載外部js文件javascript

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內容css

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,動態樣式java

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,動態寫入頁面styleapp

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);
 }
}
相關文章
相關標籤/搜索