动态向head中设置javaScript文件

前端之家收集整理的这篇文章主要介绍了动态向head中设置javaScript文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

动态向head中设置javaScript文件

文件如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <Meta NAME="Generator" CONTENT="EditPlus">
  <Meta NAME="Author" CONTENT="">
  <Meta NAME="Keywords" CONTENT="">
  <Meta NAME="Description" CONTENT="">
<script type="text/javascript">
var lastScript;
var h=document.getElementsByTagName("head")[0];
function loadScript(url){
              var f=document.createElement("script");
              var d=new Date().getTime();//用时间来做为唯一ID
                    f.type="text/javascript";
                    f.id=d;
                    f.src=url+'?'+d;
                    h.appendChild(f);//将js加入head标签
         if(lastScript&&g(lastScript))

                 g(lastScript).parentNode.removeChild(g(lastScript));//移除上一次加入的js
           lastScript=d;//修改最后一个js的id
          alert(h.innerHTML);
  }
function g(x){
      return document.getElementById(x)
  };
</script>
</head>
<body>
 <button onclick="loadScript('http://localhost/alert.js')">Test Alert</button><br />
 <button onclick="loadScript('http://localhost/info.js')">Test Info</button><br />
</body>
</html>

猜你在找的JavaScript相关文章