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

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

Jul 21, 2017 pm 03:25 PM
load

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>
Copy after login

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;
  }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP implements infinite scroll loading PHP implements infinite scroll loading Jun 22, 2023 am 08:30 AM

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

How to solve the problem that css cannot be loaded How to solve the problem that css cannot be loaded Oct 20, 2023 am 11:29 AM

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.

What should I do if Windows 7 fails to load the USB driver? What should I do if Windows 7 fails to load the USB driver? Jul 11, 2023 am 08:13 AM

When installing the win7 system, some netizens encountered a situation where loading the USB driver failed. The USB device could not be recognized in the new win7 system, and common USB flash drives, mice and other devices could not be used. So what should I do if the installation of win7 fails to load the USB driver? Let Xiaobai teach you how to solve the problem of failure to load the USB driver when installing win7. Method 1: 1. First, we turn on the computer and enter the computer system, and check the computer system version in the computer system. Confirm whether the version of the computer system is consistent with the version of the device driver. 2. After confirming the driver version, connect the USB device to the computer system. The computer system shows that the device cannot connect to the system. 3. On the connection information page, click the Help button to view the help information. 4. If the computer department

How to use JavaScript to achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? How to use JavaScript to achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? Oct 27, 2023 pm 06:30 PM

How does JavaScript achieve the infinite scroll effect of automatically loading when scrolling to the bottom of the page? The infinite scroll effect is one of the common features in modern web development. It can automatically load more content when scrolling to the bottom of the page, allowing users to obtain more data or resources without manually clicking buttons or links. In this article, we'll explore how to use JavaScript to achieve this functionality and provide specific code examples. To achieve the infinite scrolling effect of automatically loading when scrolling to the bottom of the page, it is mainly divided into the following

How to use JavaScript to automatically load more content when scrolling to the bottom of a web page? How to use JavaScript to automatically load more content when scrolling to the bottom of a web page? Oct 18, 2023 am 11:40 AM

How does JavaScript implement the function of automatically loading more content when scrolling to the bottom of a web page? Overview: Infinite scrolling is a common feature in modern internet applications. When users scroll to the bottom of the web page, more content is automatically loaded, providing a better user experience. JavaScript can help us achieve this functionality. This article will introduce specific code examples of how to use JavaScript to listen to user scroll events and load more content based on the scroll position. Specific implementation: First, in HTM

See all articles