search
HomeWeb Front-endJS TutorialSummary of method examples of dynamically loading scripts in js_javascript skills

The example in this article describes the method of dynamically loading scripts in js. Share it with everyone for your reference, the details are as follows:

Recently, the company's front-end map product needs to be divided into modules. It is hoped that users will load which module according to which function they use. This can improve the user experience.

So I searched everywhere to study the loading of js dynamic scripts, but it’s really sad! , there are almost the same articles on the Internet, 4 methods. I hate people who copy other people's results and don't add a link to the original article. Why! The point is that the last method is still a little wrong. After two days of research and information, I would like to share it with you here.

First we need a js file to be loaded. I created a package.js in a fixed folder. After opening it, I wrote a method functionOne in it. It is very simple. The code is as follows:

function functionOne(){
  alert("成功加载");
}

The subsequent html files are all created in the same directory.

Method 1: Direct document.write

Create a function1.html under the same folder with the following code:

<html>
<head>
  <title></title>
  <script type="text/javascript">
    function init()
    {
      //加载js脚本
      document.write("<script src='package.js'><\/script>");
      //加载一个按钮
      document.write("<input type=\"button\" value=\"测试运行效果\" onclick=\"operation()\"\/>");
      //如果马上使用会找不到,因为还没有加载进来,此处会报错
      functionOne();
    }
    function operation()
    {
      //可以运行,显示“成功加载”
      functionOne();
    }
  </script>
</head>
<body>
  <input type="button" value="初始化加载" onclick="init()"/>
</body>
</html>

You can write scripts to the page through document.write. As shown in the code, you can load the package.js file after clicking the button "Initial Load", but if you run the method functionOne immediately, you will not be able to find this method. Report Error, but clicking the second button ("Test Running Effect" dynamically created through document.write) found that it can be executed. At this time, the script has been loaded. Since this method is asynchronous loading (while continuing to execute the following code, an additional thread is opened to execute the script that needs to be loaded), and document.write will rewrite the interface, which is obviously not practical.

Method 2: Dynamically change the src attribute of an existing script

Create a function2.html under the same folder with the following code:

<html>
<head>
  <title></title>
  <script type="text/javascript" id="yy" src=""></script>
  <script type="text/javascript">
    function init()
    {
      yy.src = "package.js";
      //如果马上使用会找不到,因为还没有加载进来,此处会报错
      functionOne();
    }
    function operation()
    {
      //可以运行,显示“成功加载”
      functionOne();
    }
  </script>
</head>
<body>
  <input type="button" value="测试按钮" onclick="init()"/>
  <input type="button" value="测试运行效果" onclick="operation()"/>
</body>
</html>

The advantage of this method is that it does not change the interface elements and does not rewrite the interface elements. However, it is also loaded asynchronously and will have the same problem.

Method 3: Dynamically create script elements (asynchronous)

Create a function3.html under the same folder with the following code:

<html>
<head>
  <title></title>
  <script type="text/javascript">
    function init()
    {
      var myScript= document.createElement("script");
      myScript.type = "text/javascript";
      myScript.src="package.js";
      document.body.appendChild(myScript);
      //如果马上使用会找不到,因为还没有加载进来
      functionOne();
    }
    function operation()
    {
      //可以运行,显示“成功加载”
      functionOne();
    }
  </script>
</head>
<body>
  <input type="button" value="测试按钮" onclick="init()"/>
  <input type="button" value="测试运行效果" onclick="operation()"/>
</body>
</html>

The advantage of this method compared to the second method is that there is no need to write a script tag in the interface at the beginning. The disadvantage is asynchronous loading and the same problem.

These three methods are all executed asynchronously, so while loading these scripts, the scripts on the main page continue to run. If the above methods are used, the following code will not have the expected effect.

However, you can add an alert in front of functionOne to block the running of the main page script. Then you find that functionOne can run, or your later code needs to be executed under another button. Do it step by step, or else Just define a timer and execute the following code after a fixed time. However, it is definitely impossible to use these methods in the project.

In fact, the third method can be changed to synchronous loading with a few changes.

Method 4: Dynamically create script elements (synchronously)

Create a function4.html under the same folder with the following code:

<html>
<head>
  <title></title>
  <script type="text/javascript">
    function init()
    {
      var myScript= document.createElement("script");
      myScript.type = "text/javascript";
      myScript.appendChild(document.createTextNode("function functionOne(){alert(\"成功运行\"); }"));
      document.body.appendChild(myScript);
      //此处发现可以运行
      functionOne();
    }
  </script>
</head>
<body>
  <input type="button" value="测试按钮" onclick="init()"/>
</body>
</html>

This method does not load external js files, but adds sub-items to myScript. In Firefox, Safari, Chrome, Opera and IE9, this code works fine. However, it will cause errors in IE8 and lower versions. IE treats <script> as a special element and does not allow DOM access to its child nodes. However, you can use the text attribute of the <script> element to formulate js code, as in the following example: </script>

var myScript= document.createElement("script");
myScript.type = "text/javascript";
myScript.text = "function functionOne(){alert(\"成功运行\"); }";
document.body.appendChild(myScript);
//此处可以运行
functionOne();

The code modified in this way can run in IE, Firefox, Opera and Safari3 and later versions. Versions of Safari prior to 3.0, although they did not correctly support the text attribute, did allow the use of text node technology to specify code. If you need to be compatible with earlier versions of Safari, you can use the following code:

var myScript= document.createElement("script");
myScript.type = "text/javascript";
var code = "function functionOne(){alert(\"成功运行\"); }";
try{
    myScript.appendChild(document.createTextNode(code));
}
catch (ex){
    myScript.text = code;
}
document.body.appendChild(myScript);
//此处发现可以运行
functionOne();

Here, first try the standard DOM text node method, because all browsers except IE8 and below support this method. If this line of code throws an error, it means IE8 or below, so the text attribute must be used. The whole process can be represented by the following function:

function loadScriptString(code)
{
  var myScript= document.createElement("script");
  myScript.type = "text/javascript";
  try{
    myScript.appendChild(document.createTextNode(code));
  }
  catch (ex){
    myScript.text = code;
  }
  document.body.appendChild(myScript);
}

You can then use this method elsewhere to load the code you need to use. In fact, executing the code this way is the same as passing the same string to eval() in the global function. But we can only use string-form codes here, and there are limitations. Users generally want to provide methods in the form of loadScriptAddress("package.js"), so we need to continue discussing.

Method 5: XMLHttpRequest/ActiveXObject asynchronous loading

Create a function5.html under the same folder with the following code:

<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只有IE里面才有,其他浏览器大部分支持XMLHttpRequest,通过此办法我们可以实现动态加载脚本了,不过是异步加载,也没法运行functionOne,第二次就可以运行了,但是可惜的是在IE、Firefox、Safari下可以运行,在Opera、Chrome下会出错,Chrome下的错误如下:

不过只要发布之后在Chrome和Opera下就不会出现错误了。

其实这里把open里面设置为false就是同步加载了,同步加载不需要设置onreadystatechange事件。

方法六:XMLHttpRequest/ActiveXObject同步加载 

在这里我把一些情况考虑在内,写成了一个方法,封装为loadJS.js,方便以后直接调用,代码如下:

/**
 * 同步加载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;
  }
}

此处考虑到了浏览器的兼容性以及当为Chrome、Opera时必须是发布,注释还是写的比较清楚的,以后需要加载某个js文件时,只需要一句话就行了,如loadJS("myJS","package.js")。方便实用。

如果想要实现不发布还非要兼容所有浏览器,至少我还没找出这样的同步加载的办法,我们只能通过异步加载开出回调函数来实现。

方法七:回调函数方式

在同一个文件夹下面创建一个function7.html,代码如下:

<html>
<head>
  <title></title>
  <script type="text/javascript">
    function init()
    {
      //加载package.js文件,设置script的id为yy
      loadJs("yy","package.js",callbackFunction);
    }
    function callbackFunction()
    {
      functionOne();
    }
    function loadJs(sid,jsurl,callback){
      var nodeHead = document.getElementsByTagName('head')[0];
      var nodeScript = null;
      if(document.getElementById(sid) == null){
        nodeScript = document.createElement('script');
        nodeScript.setAttribute('type', 'text/javascript');
        nodeScript.setAttribute('src', jsurl);
        nodeScript.setAttribute('id',sid);
        if (callback != null) {
          nodeScript.onload = nodeScript.onreadystatechange = function(){
            if (nodeScript.ready) {
              return false;
            }
            if (!nodeScript.readyState || nodeScript.readyState == "loaded" || nodeScript.readyState == 'complete') {
              nodeScript.ready = true;
              callback();
            }
          };
        }
        nodeHead.appendChild(nodeScript);
      } else {
        if(callback != null){
          callback();
        }
      }
    }
  </script>
</head>
<body>
  <input type="button" value="测试按钮" onclick="init()"/>
</body>
</html>

这种方式所有浏览器都支持,但是后面的代码必须放在回调函数里面,也就是异步加载了。看需求使用把!我还是比较喜欢第六种方法的。如果是异步加载的话,方法还有好几种,不过我的出发点是希望实现同步加载,这里就不对异步加载做总结了。

希望本文所述对大家JavaScript程序设计有所帮助。

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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool