事情是这样子的:
有许多类似页面,都有一个<script src='1.js'>.
他们单独显示都没有问题.
可是首页上,是许多单独的页组合起来的,就是wordpress.
这种情况下如何避免重复装入同一个js 文件?
类似于php的require_once.

解决方案 »

  1.   

    这事情放到首页的onload()里做:
    window.onload=function(){
      var b=false
      var a=document.getElementsByTagName('SCRIPT')
      for(var i=0;i<a.length;i++){
        if(!b){
          b=(a[i].src&&a[i].src=='1.asp')?true:false;
        }
        else{
          if(a[i].src&&a[i].src=='1.asp'){
            a[i].parent.removeChild(a[i])
          }
        }
      }
    }
      

  2.   

    在js第一行写上 document.write('<script type="text/javascript" src="1.js">');
      

  3.   

    谢啊,只能改单页.不能改首页,不过如果实在没有办法,会尝试着去改一下.因为wordpress的首页难改.对于我来说.
      

  4.   

    你这个不对吧。如果是removeChild,说明已经在页面上了。
      

  5.   

    function requireOnce(scriptPath) {

    var scripts = document.getElementsByTagName("script");

    for (var index = 0; index < scripts.length; index++) {

    if (scripts[index].src.lastIndexOf(scriptPath) != -1) {
    return;
    }
    }
    var scriptTag = document.createElement("script");
    scriptTag.type = "text/javascript";
    scriptTag.src = scriptPath;
    var headTag = document.getElementsByTagName("head")[0];
    headTag.appendChild(scriptTag);
    }
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-31j">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/common.js"></script>
    <script type="text/javascript">
    requireOnce("js/glUtils.js");
    requireOnce("js/glUtils.js");
    requireOnce("js/glUtils.js");
    requireOnce("js/glUtils.js");
    </script>
    </head>
    <body></body>
    </html>试试看
      

  6.   

    5,6楼:你我的思路不同。我的方法是让所有的1.JS全部加载,然后只需要在首页的window.onload()里保留一个1.JS,其余删除。这样做的好处是只改首页一个页面;你的那个需要改动首页以及它所有的包含的页面,不划算!
      

  7.   

    当然最完美的做法是首页也用这个函数,函数内部维护一个数组来判断,但是既然做不到,我就折中了下。在判断的时候用lastIndexOf。当然如果你有更好的做法。欢迎提出。。