Home > Web Front-end > JS Tutorial > body text

Detailed explanation of synchronous and asynchronous dynamic creation of script element instances in javascript

伊谢尔伦
Release: 2017-07-21 15:21:04
Original
2606 people have browsed it

Dynamic creation of script elements (asynchronous)

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

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

The advantage of this method compared to the second one is There is no need to write a script tag in the interface from the beginning. The disadvantage is still asynchronous loading, which has 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.

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

In fact, the third method can be changed to synchronous loading with a little change.

Dynamic creation of script elements (synchronous)

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

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

This method does not load external js files , but added subkeys to myScript. In Firefox, Safari, Chrome, Opera and IE9, this code works fine. But it will cause errors in IE8 and below versions. IE treats

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template