function init() { // Load the package.js file and set the script's id to yy ajaxP"/> function init() { // Load the package.js file and set the script's id to yy ajaxP">

Home  >  Article  >  Web Front-end  >  Detailed explanation of XMLHttpRequest/ActiveXObject synchronization and asynchronous loading usage examples

Detailed explanation of XMLHttpRequest/ActiveXObject synchronization and asynchronous loading usage examples

伊谢尔伦
伊谢尔伦Original
2017-07-21 15:25:542923browse

XMLHttpRequest/ActiveXObject asynchronous loading

Create a function5.html under the same folder, the code is as follows:

<html>
<head>
  <title></title>
  <script type="text/javascript">
    function init()
    {
      //加载package.js文件,设置script的id为yy
      ajaxPage("yy","package.js");
      //此方法为package.js里面的方法,此处执行方法成功
      functionOne();
    }
    function ajaxPage(sId,url)
    {
      var oXmlHttp = getHttpRequest();
      oXmlHttp.onreadystatechange = function()
      {
        //4代表数据发送完毕
        if ( oXmlHttp.readyState == 4 )
        {
          //0为访问的本地,200代表访问服务器成功,304代表没做修改访问的是缓存
          if(oXmlHttp.status == 200 || oXmlHttp.status == 0 || oXmlHttp.status == 304)
          {
            includeJS(sId,oXmlHttp.responseText);
          }
          else
          {
          }
        }
      }
      oXmlHttp.open("GET",url,true);
      oXmlHttp.send(null);
    }
    function getHttpRequest()
    {
      if(window.ActiveXObject)//IE
      {
        return new ActiveXObject("MsXml2.XmlHttp");
      }
      else if(window.XMLHttpRequest)//其他
      {
        return new XMLHttpRequest();
      }
    }
    function includeJS(sId,source)
    {
      if((source != null)&&(!document.getElementById(sId)))
      {
        var myHead = document.getElementsByTagName("HEAD").item(0);
        var myScript = document.createElement( "script" );
        myScript.language = "javascript";
        myScript.type = "text/javascript";
        myScript.id = sId;
        try{
          myScript.appendChild(document.createTextNode(source));
        }
        catch (ex){
          myScript.text = source;
        }
        myHead.appendChild( myScript );
      }
    }
  </script>
</head>
<body>
  <input type="button" value="测试按钮" onclick="init()"/>
</body>
</html>

ActiveXObject is only available in IE, most other browsers support XMLHttpRequest , through this method we can dynamically load the script, but it is asynchronous loading, and functionOne cannot be run. It can be run the second time, but unfortunately it can run under IE, Firefox, Safari, and under Opera and Chrome There will be errors, but as long as it is released, there will be no errors under Chrome and Opera.

In fact, setting open to false here means synchronous loading. Synchronous loading does not require setting the onreadystatechange event.

XMLHttpRequest/ActiveXObject synchronous loading

Here I took some situations into consideration and wrote a method, encapsulated as loadJS.js, to facilitate direct calling in the future. The code is as follows:

/**
 * 同步加载js脚本
 * @param id  需要设置的<script>标签的id
 * @param url  js文件的相对路径或绝对路径
 * @return {Boolean}  返回是否加载成功,true代表成功,false代表失败
 */
function loadJS(id,url){
  var xmlHttp = null;
  if(window.ActiveXObject)//IE
  {
    try {
      //IE6以及以后版本中可以使用
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      //IE5.5以及以后版本可以使用
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  else if(window.XMLHttpRequest)//Firefox,Opera 8.0+,Safari,Chrome
  {
    xmlHttp = new XMLHttpRequest();
  }
  //采用同步加载
  xmlHttp.open("GET",url,false);
  //发送同步请求,如果浏览器为Chrome或Opera,必须发布后才能运行,不然会报错
  xmlHttp.send(null);
  //4代表数据发送完毕
  if ( xmlHttp.readyState == 4 )
  {
    //0为访问的本地,200到300代表访问服务器成功,304代表没做修改访问的是缓存
    if((xmlHttp.status >= 200 && xmlHttp.status <300) || xmlHttp.status == 0 || xmlHttp.status == 304)
    {
      var myHead = document.getElementsByTagName("HEAD").item(0);
      var myScript = document.createElement( "script" );
      myScript.language = "javascript";
      myScript.type = "text/javascript";
      myScript.id = id;
      try{
        //IE8以及以下不支持这种方式,需要通过text属性来设置
        myScript.appendChild(document.createTextNode(xmlHttp.responseText));
      }
      catch (ex){
        myScript.text = xmlHttp.responseText;
      }
      myHead.appendChild( myScript );
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    return false;
  }
}

Taking into account the compatibility of browsers and the need to publish when it is Chrome or Opera, the comments are written relatively clearly. When you need to load a js file in the future, you only need one sentence, such as loadJS( "myJS","package.js"). Convenient and practical.

The above is the detailed content of Detailed explanation of XMLHttpRequest/ActiveXObject synchronization and asynchronous loading usage examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn