Dynamically loading an external JavaScript or CSS file

原文:   Dynamically loading an external JavaScript or CSS file

 

通过javascript动态加载css文件和javascript文件,主要是通过javascript在HTML的Head标签中间插入下面的代码,达到引入css和javascript效果

<link href="SNJStyles.css" type="text/css" rel="stylesheet">

<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>

实现代码:

 1 function loadjscssfile(filename, filetype){
 2  if (filetype=="js"){ //if filename is a external JavaScript file
 3   var fileref=document.createElement('script')
 4   fileref.setAttribute("type","text/javascript")
 5   fileref.setAttribute("src", filename)
 6  }
 7  else if (filetype=="css"){ //if filename is an external CSS file
 8   var fileref=document.createElement("link")
 9   fileref.setAttribute("rel", "stylesheet")
10   fileref.setAttribute("type", "text/css")
11   fileref.setAttribute("href", filename)
12  }
13  if (typeof fileref!="undefined")
14   document.getElementsByTagName("head")[0].appendChild(fileref)
15 }
16 
17 // 使用例子
18 loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
19 loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
20 loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

 

你可能感兴趣的:(JavaScript)