当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 用ajax动态加载需要的js文件

用ajax动态加载需要的js文件

2017年12月12日  | 移动技术网IT编程  | 我要评论

习惯了用java,在java中,需要某个类直接import就可以了,所以做javascript的时候也想实现这个效果。

  前段时间,用了下dojo,里面的dojo.require的功能很不错,一看代码,晕了,一大堆东西,唉~还是自己写个简单点的,dojo.require可以引入包,我就只做一个导入js文件的。

  开始用的document.write,执行顺序不对了,这是在后面进行导入,而我们总是在前面执行中就需要导入的js,这样,执行中就会报“某某未定义”,就是顺序问题了。

  接着,我就想用ajax同步(注意:不是异步)调用远程js文件,这里有个问题,就是我们要js文件的时候,不是用绝对路径,就是相对路径,用相对路径的话,以哪个为参照呢?可以用调用js的那个文件为参照,也可以以实现调用功能的js文件为参照,这里,我选择写个 js,实现按需调用其它js,参照也选它。经过一番修改,路径问题解决。但是,读取过来的数据中文会有乱码问题,好在我们做东西都用utf-8(因为要国际化),所以这里避过了。

  远程js内容取到后,就要执行,用eval执行后,发现还是取不到远程js里定义的内容,怪了,猛alert一番后,发现执行eval的上下文范围有问题,我们要的是js在window对象中执行,嗯?window有什么方法没?一找,哈,有个window.execscript方法,ok,试一下,成功,yeah~后来发现在firefox下,不能用window.execscript,找了一下,用window.eval,用法和ie下的window.execscript类似。但是只用window.eval的时候,在ie下有时候会出问题,所以就两种一起用了。

  下面是实现远程js安调用的那个js:env.js,我已经习惯用oo写js了

 /** 
 * @author zxub 2006-06-01 
 * 状态信息显示类,用var status=new function()定义,可以静态引用其中的方法 
 * 一般情况下为function status(),这样不能静态引用其中的方法,需要通过对象来引用 
 */ 
var status=new function() 
{ 
  this.statusdiv=null; 
   
  /** 
   * 初始化状态显示层 
   */ 
  this.init=function() 
  { 
    if (this.statusdiv!=null) 
    { 
      return; 
    } 
    var body = document.getelementsbytagname("body")[0]; 
    var div = document.createelement("div"); 
    div.style.position = "absolute"; 
    div.style.top = "50%"; 
    div.style.left = "50%"; 
    div.style.width = "280px"; 
    div.style.margin = "-50px 0 0 -100px";     
    div.style.padding = "15px"; 
    div.style.backgroundcolor = "#353555"; 
    div.style.border = "1px solid #cfcfff"; 
    div.style.color = "#cfcfff"; 
    div.style.fontsize = "14px"; 
    div.style.textalign = "center"; 
    div.id = "status"; 
    body.appendchild(div); 
    div.style.display="none"; 
    this.statusdiv=document.getelementbyid("status"); 
  } 
   
  /** 
   * 设置状态信息 
   * @param _message:要显示的信息 
   */   
  this.showinfo=function(_message) 
  {    
    if (this.statusdiv==null) 
    { 
      this.init(); 
    }  
    this.setstatusshow(true); 
    this.statusdiv.innerhtml = _message;     
  } 
    
  /** 
   * 设置状态层是否显示 
   * @param _show:boolean值,true为显示,false为不显示 
   */  
  this.setstatusshow=function(_show) 
  {    
    if (this.statusdiv==null) 
    { 
      this.init(); 
    }  
    if (_show) 
    { 
      this.statusdiv.style.display=""; 
    } 
    else 
    { 
      this.statusdiv.innerhtml=""; 
      this.statusdiv.style.display="none"; 
    } 
  } 
} 

/** 
 * @author zxub 
 * 用于存放通道名称及通信对象的类,这样可以通过不同通道名称来区分不同的通信对象 
 */ 
function httprequestobject() 
{ 
  this.chunnel=null; 
  this.instance=null; 
} 

/** 
 * @author zxub 
 * 通信处理类,可以静态引用其中的方法 
 */ 
var request=new function() 
{ 
  this.showstatus=true; 
   
  //通信类的缓存 
  this.httprequestcache=new array(); 
   
  /** 
   * 创建新的通信对象 
   * @return 一个新的通信对象 
   */ 
  this.createinstance=function() 
  { 
    var instance=null; 
    if (window.xmlhttprequest) 
    { 
      //mozilla 
      instance=new xmlhttprequest(); 
      //有些版本的mozilla浏览器处理服务器返回的未包含xml mime-type头部信息的内容时会出错。因此,要确保返回的内容包含text/xml信息 
      if (instance.overridemimetype) 
      { 
        instance.overridemimetype="text/xml"; 
      } 
    } 
    else if (window.activexobject) 
    { 
      //ie 
      var msxml = ['msxml2.xmlhttp.5.0', 'microsoft.xmlhttp', 'msxml2.xmlhttp.4.0', 'msxml2.xmlhttp.3.0', 'msxml2.xmlhttp']; 
      for(var i = 0; i < msxml.length; i++) 
      { 
        try 
        { 
          instance = new activexobject(msxml[i]); 
          break; 
        } 
        catch(e) 
        {           
        } 
      } 
    } 
    return instance; 
  } 
   
  /** 
   * 获取一个通信对象 
   * 若没指定通道名称,则默认通道名为"default" 
   * 若缓存中不存在需要的通信类,则创建一个,同时放入通信类缓存中 
   * @param _chunnel:通道名称,若不存在此参数,则默认为"default" 
   * @return 一个通信对象,其存放于通信类缓存中 
   */ 
  this.getinstance=function(_chunnel) 
  { 
    var instance=null; 
    var object=null; 
    if (_chunnel==undefined)//没指定通道名称 
    { 
      _chunnel="default"; 
    } 
    var getone=false; 
    for(var i=0; i<this.httprequestcache; i++) 
    { 
      object=httprequestobject(this.httprequestcache[i]); 
      if (object.chunnel==_chunnel) 
      { 
        if (object.instance.readystate==0 || object.instance.readystate==4) 
        { 
          instance=object.instance; 
        } 
        getone=true; 
        break;           
      } 
    } 
    if (!getone) //对象不在缓存中,则创建 
    { 
      object=new httprequestobject(); 
      object.chunnel=_chunnel; 
      object.instance=this.createinstance(); 
      this.httprequestcache.push(object); 
      instance=object.instance; 
    }      
    return instance; 
  } 
   
  /** 
   * 客户端向服务端发送请求 
   * @param _url:请求目的 
   * @param _data:要发送的数据 
   * @param _processrequest:用于处理返回结果的函数,其定义可以在别的地方,需要有一个参数,即要处理的通信对象 
   * @param _chunnel:通道名称,默认为"default" 
   * @param _asynchronous:是否异步处理,默认为true,即异步处理 
   */ 
  this.send=function(_url,_data,_processrequest,_chunnel,_asynchronous) 
  { 
    if (_url.length==0 || _url.indexof("?")==0) 
    { 
      status.showinfo("由于目的为空,请求失败,请检查!"); 
      window.settimeout("status.setstatusshow(false)",3000); 
      return; 
    } 
    if (this.showstatus) 
    { 
      status.showinfo("请求处理中,请稍候");  
    } 
    if (_chunnel==undefined || _chunnel=="") 
    { 
      _chunnel="default"; 
    } 
    if (_asynchronous==undefined) 
    { 
      _asynchronous=true; 
    } 
    var instance=this.getinstance(_chunnel); 
    if (instance==null) 
    { 
      status.showinfo("浏览器不支持ajax,请检查!") 
      window.settimeout("status.setstatusshow(false)",3000); 
      return; 
    }  
    if (_asynchronous==true && typeof(_processrequest)=="function") 
    { 
      instance.onreadystatechange=function() 
      { 
        if (instance.readystate == 4) // 判断对象状态 
        { 
          if (instance.status == 200) // 信息已经成功返回,开始处理信息 
          {          
            _processrequest(instance); 
            status.setstatusshow(false); 
            request.showstatus=true;           
          } 
          else 
          { 
            status.showinfo("您所请求的页面有异常,请检查!"); 
            window.settimeout("status.setstatusshow(false)",3000); 
          } 
        } 
      } 
    } 
    //_url加一个时刻改变的参数,防止由于被浏览器缓存后同样的请求不向服务器发送请求 
    if (_url.indexof("?")!=-1) 
    { 
      _url+="&requesttime="+(new date()).gettime(); 
    } 
    else 
    { 
      _url+="?requesttime="+(new date()).gettime(); 
    } 
    if (_data.length==0) 
    { 
      instance.open("get",_url,_asynchronous);      
      instance.send(null);       
    } 
    else 
    { 
      instance.open("post",_url,_asynchronous); 
      instance.setrequestheader("content-length",_data.length); 
      instance.setrequestheader("content-type","application/x-www-form-urlencoded"); 
      instance.send(_data); 
    } 
    if (_asynchronous==false && typeof(_processrequest)=="function") 
    { 
      _processrequest(instance); 
      if (request.showstatus) 
      { 
        status.setstatusshow(false); 
      } 
      else 
      { 
        request.showstatus=true; 
      } 
    } 
  } 
   
  /** 
   * 间隔一段时间持续发送请求,只用于异步处理,只用于get方式 
   * @param _interval:请求间隔,以毫秒计 
   * @param _url:请求地址 
   * @param _processrequest:用于处理返回结果的函数,其定义可以在别的地方,需要有一个参数,即要处理的通信对象 
   * @param _chunnel:通道名称,默认为"defaultinterval",非必添 
   */ 
  this.intervalsend=function(_interval,_url,_processrequest,_chunnel) 
  { 
    var action=function() 
    { 
      if (_chunnel==undefined) 
      { 
        _chunnel="defaultinterval"; 
      } 
      var instance=request.getinstance(_chunnel); 
      if (instance==null) 
      { 
        status.showinfo("浏览器不支持ajax,请检查!") 
        window.settimeout("status.setstatusshow(false)",3000); 
        return; 
      } 
      if (typeof(_processrequest)=="function") 
      { 
        instance.onreadystatechange=function() 
        { 
          if (instance.readystate == 4) // 判断对象状态 
          { 
            if (instance.status == 200) // 信息已经成功返回,开始处理信息 
            { 
              _processrequest(instance); 
            } 
            else 
            { 
              status.showinfo("您所请求的页面有异常,请检查!"); 
              window.settimeout("status.setstatusshow(false)",3000); 
            } 
          } 
        } 
      } 
      //_url加一个时刻改变的参数,防止由于被浏览器缓存后同样的请求不向服务器发送请求 
      if (_url.indexof("?")!=-1) 
      { 
        _url+="&requesttime="+(new date()).gettime(); 
      } 
      else 
      { 
        _url+="?requesttime="+(new date()).gettime(); 
      } 
      instance.open("get",_url,true); 
      instance.send(null); 
    } 
    window.setinterval(action,_interval);     
  } 
} 

var env=new function() 
{   
  this.funclist=new array(); 
     
  this.envpath=null; 
   
  this.getpath=function() 
  { 
    this.envpath=document.location.pathname; 
    this.envpath=this.envpath.substring(0,this.envpath.lastindexof("/")+1);     
    var _scripts=document.getelementsbytagname("script"); 
    var _envpath=null; 
    var _scriptsrc=null; 
    for (var i=0; i<_scripts.length; i++) 
    { 
      _scriptsrc=_scripts[i].getattribute("src"); 
      if (_scriptsrc && _scriptsrc.indexof("env.js")!=-1) 
      { 
        break; 
      } 
    } 
    if (_scriptsrc!=null) 
    { 
      if (_scriptsrc.charat(0)=='/') 
      { 
        this.envpath=_scriptsrc.substr(0,_scriptsrc.length-6); 
      } 
      else 
      { 
        this.envpath=this.envpath+_scriptsrc.substr(0,_scriptsrc.length-6); 
      } 
    }     
  } 
  this.getpath();   
   
  /** 
   * 按需获取需要的js文件 
   * @param _jsname:js文件路径,若为相对路径,则是对应env.js的相对路径,也可以用绝对路径 
   * @param _language:对返回函数进行处理的语言,默认为jscript,可不填 
   */ 
  this.require=function(_jsname,_language) 
  { 
    var _absjsname=null; 
    if (_jsname.charat(0)=='/') 
    { 
      _absjsname=_jsname; 
    } 
    else 
    { 
      _absjsname=this.envpath+_jsname; 
    }     
    if (!env.funclist[_absjsname]) 
    { 
      env.funclist[_absjsname]="finished";  
      var processjs=function(_instance) 
      { 
        //为兼容firefox做判断 
        if (_language!=undefined) 
        { 
          if (window.execscript) 
          { 
            window.execscript(_instance.responsetext,_language); 
          } 
          else 
          { 
            window.eval(_instance.responsetext,_language); 
          }                     
        } 
        else 
        { 
          if (window.execscript) 
          { 
            window.execscript(_instance.responsetext); 
          } 
          else 
          { 
            window.eval(_instance.responsetext); 
          }           
        }         
      } 
      request.showstatus=false; 
      request.send(_absjsname,"",processjs,"",false); 
    } 
  } 
   
  /** 
   * 该函数的效果是在应用它的script块后加一个script块 
   * 是由document.write在script块中的执行顺序决定的 
   */ 
  this.getjs=function(_jsname) 
  { 
    if (!env.funclist[_jsname]) 
    { 
      env.funclist[_jsname]="finished"; 
      document.write('<scr'+'ipt type="text/javascript" src="'+_jsname+'"></'+'scr'+'ipt>'); 
    } 
  } 
} 

/** 
 * ajax调用远程页面后,远程页面中script块未执行的处理 
 */ 
function reloadjs(_language) 
{ 
  var _c=document.getelementsbytagname("script"); 
  for (var i=0;i<_c.length;i++) 
  { 
    if (_c[i].src) 
    { 
      var _s=document.createelement("script"); 
      _s.type="text/javascript"; 
      _s.src=_c[i].src; 
      //为兼容firefox不用_c[0].insertadjacentelement("beforebegin",_s) 
      _c[0].parentnode.insertbefore(_s,_c[0]);       
      _c[i].parentnode.removechild(_c[i]); 
    } 
    else if (_c[i].text) 
    { 
      if (_language!=undefined) 
      { 
        if (window.execscript) 
        { 
          window.execscript(_c[i].text,_language); 
        } 
        else 
        { 
          window.eval(_c[i].text,_language); 
        } 
      } 
      else 
      { 
        if (window.execscript) 
        { 
          window.execscript(_c[i].text); 
        } 
        else 
        { 
          window.eval(_c[i].text); 
        } 
      } 
    } 
  } 
}   

需要引用别的js的时候,就加上如env.require("cookie.js"),或env.require("/common/cookie.js"),是用相对路径还是绝对路径就看喜好了,env.require可用在页面模板中,也可用在js文件中,但一定要保证执行时env.js被显式引入。多次env.require同一个js(不管用相对还是绝对),只有第一次会加载,所以不会重复。

  按个人应用不一样,可以修改一点,主体思想就这样了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网