日期:2014-05-16  浏览次数:20375 次

动态加载JS的方式

1.使用AJax技术动态加载JS文件

?

function ajaxRequest(filename)
{ 
   try{
      ajaxreq = new XMLHttpRequest();
	 // alert("rigth");	  	  
   }catch(error)
   {
     try{
            ajaxreq = new ActiveXObject("Microsoft.XMLHTTP");	 
	 }catch(error)
	 {
	   alert("error");
	   return false;
	 }
   }
   ajaxreq.open("GET",filename);
   ajaxreq.onreadystatechange = ajaxResponse;
   ajaxreq.send(null);
}

function ajaxResponse()
{
   if(ajaxreq.readyState !=4)
   {     
	 //alert("!=4");
     return;
   }
    if(ajaxreq.status == 0)   //如果读取本地JS文件,ajax没有发送http请求,返回的status == 0时代表请求完成。
   {      
       IncludeJS("GPS","js/GPS.js", ajaxreq.responseText); 
   }
   else 
   {
     alert("Request failed:"+ ajaxreq.status);	 
   }   
   return true;
}
function IncludeJS(sid,fileUrl, source) 
{ 
     var element = document.getElementById(sid);	
     var head = document.getElementsByTagName('head').item(0); 	 
     if(element)
	 {    	
        head.removeChild(element);	  
	 }
	 
     if (( source != null )){
    	var oHead = document.getElementsByTagName('head').item(0); 
        var oScript = document.createElement( "script" ); 
        oScript.language = "javascript"; 
        oScript.type = "text/javascript"; 
        oScript.id = sid;		
        oScript.defer = true; 
        oScript.text = source; 
		//alert("oScript.text:" + oScript.text);
        oHead.appendChild( oScript );         		
					 
		}
			
} 

?2. 动态加载script标记

?

function LoadJS()
{
    var id = "Route";
    var script = document.createElement("script"); 
    script.id = id; 
    script.type = "text/javascript"; 
script.src = "http://domain/SmartLib/TestServlet";
    if (callback) 
    {     
     script.onload = script.onreadystatechange = function() 
        { 
            script.onreadystatechange = script.onload = null; 
            callback(); 
        }; 
	}
	
    var head = document.getElementsByTagName('head').item(0); 
    head.appendChild (script); 
	
}

function callback()
{
//解析返回的数据
}

?

注: 在IE下,readyState的值可能为一下几个:

"uninitialized"--原始状态

"loading" -- 下载数据中

"loaded" -- 下载完成

"interactive"-- 还未执行完毕

"complete" --脚本执行完毕

在IE中可以通过script.onreadystatechange = function(){}捕获状态的变化,在function中,通过script.readyState的状态来做相应的处理。

但是,在Firefox中,则没有script.readyState属性,一般通过script.onload = function(){}来动态加载script.