動態載入外部css或js檔案

來源:互聯網
上載者:User

 

function loadjscssfile(filename, filetype){
if (filetype=="js"){ //判斷檔案類型
  var fileref=document.createElement('script')//建立標籤
  fileref.setAttribute("type","text/javascript")//定義屬性type的值為text/javascript
  fileref.setAttribute("src", filename)//檔案的地址
}
else if (filetype=="css"){ //判斷檔案類型
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //開啟頁面時瀏覽器動態負載檔案
loadjscssfile("javascript.php", "js") // 開啟頁面時瀏覽器動態載入"javascript.php" ,
loadjscssfile("mystyle.css", "css") //開啟頁面時瀏覽器動態載入.css 檔案

var filesadded="" //儲存已經繫結檔案名字的陣列變數
function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("["+filename+"]")==-1){// indexOf判斷數組裡是否有某一項
  loadjscssfile(filename, filetype)
  filesadded+="["+filename+"]" //把檔案名稱字添加到filesadded
}
else
  alert("file already added!")//如果已經存在就提示
}
checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.