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>

实现代码:

 function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
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") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file
上一篇:NodeJS连接MongoDB数据库时报错


下一篇:使用属性android:onClick,出现异常NoSuchMethodException