首頁 >web前端 >js教程 >動態載入js和css(外部檔案)_javascript技巧

動態載入js和css(外部檔案)_javascript技巧

WBOY
WBOY原創
2016-05-16 17:36:48880瀏覽
複製程式碼 程式碼如下:

//動態載入外部js檔案
var flag = true;
if( flag ){
loadScript( "js/index.js" );
};
function loadScript( url ){
var script = document.createElement( "script" ) ;
script.type = "type/javascipt";
script.src = url;
document.getElementsByTagName( "head" )[0].appendChild( script );
};
// 動態載入js
if( flag ){
var script = document.createElement( "script" );
script.type = "text/javascript";
script.text = " ";
document.getElementsByTagName( "head" )[0].appendChild( script );
};
// 動態載入外部css樣式
if( flag ){
loadCss( "css/base.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樣式
if( flag ){
var style = document.createElement( "style" );
style.type = "text/css";
document.getElementsByTagName( "headhead " )[0].appendChild( style );
var sheet = document.styleSheets[0];
insertRules( sheet,"#gaga1","background:#f00",0 );
} ;
function insertRules( sheet,selectorTxt,cssTxt,position ){
if( sheet.insertRule ){ // 判斷非IE瀏覽器
sheet.insertRule( selectorTxt "{" cssTx"}" );
}else if( sheet.addRule ){ //判斷是否為IE瀏覽器
sheet.addRule( selectorTxt ,cssTxt ,position )
}
}
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn