Dynamically added javascript for immediate execution

I am dynamically adding a script to a page using the DOM.

  • If I add text to the script (for example script.text = "...";

    ), it runs immediately.

  • But if I add an external script (for example script.src = "...";

    ), it runs after my script finishes.

So in the example below I will get

"0 1 2"

and

"3 3 3"

respectively.

(1.js contains the same line - "document.body.innerHTML += i"

)

<body>
  <script>
    for (i = 0; i < 3; i++) {
      var script = document.createElement('script');
      script.src = "1.js";
      //  script.text = "document.body.innerHTML += i";
      document.body.append(script);
    };
  </script>
</body>

      

I don't understand why it works this way and how do I run 1.js right after adding it?

+3


source to share


2 answers


After trying many times, I think it has something to do with browser parsing. When you add script

dynamically, if specified src

, its content will not be loaded and run immediately. The execution time of its content is different with the browser

The following code works in chrome, firefox and IE8:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    var script = document.createElement('script')
    script.src = './test.js'  //test.js   alert(2)
    document.body.appendChild(script)
    alert(3)
</script>
<script>
  alert(8)
</script>
</body>
</html>
      

Run code


Result:

In IE8, Firefox, the sequence alert

is3 2 8



In Chrome, the sequence alert

is3 8 2

Conclusion:

In IE8 and Firefox,

the content of your add script

will be dynamically run after the current script is fully executed.

In Chrome,

the content of your add script

will be dynamically started after loading other content.

+1


source


The dynamic loading of external scripts is queued to be requested through the browser. This means that they are not executed immediately after loading.

W3 HTML5 spec Scripting section:



If an element has a src attribute , it does not have an async attribute, and the force-async flag is not set

The element should be added to the end of the list of scripts to be executed as soon as possible associated with the Document script element at the time the script algorithm is running .

+1


source







All Articles