Illia
Illia

Reputation: 51

Dynamically added javascript to do immediate execution

I'm dynamically adding script to the page using DOM.

  1. If I add script text (e.g. script.text = "...";) it runs immediately.

  2. But, if I add an external script (e.g. script.src = "...";) it'll run after my script finishes.

So in example below I'll get

"0 1 2"

and

"3 3 3"

respectively.

( 1.js contains same string - "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 do not understand why it works this way, and how do I run 1.js immediately after adding?

Upvotes: 5

Views: 1183

Answers (2)

revo
revo

Reputation: 48751

Dynamic loading of external scripts are queued in order they are requested through browser. It means they are not executed immediately after being downloaded.

W3 HTML5 spec Scripting section:

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

The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

Upvotes: 2

Kermit
Kermit

Reputation: 1062

After trying many times, I think it's related to parse of the browser.when you add script dynamically, if src is specified, its content won't be loaded and ran immediately.the runtime of its content is different with the browser

Following code is running 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>

The result:

In IE8, Firefox, the sequence of alert is 3 2 8

IN Chrome, the sequence of alert is 3 8 2

The conclusion:

In IE8 and Firefox,

the content of you add script dynamically will be running after the current script run completely.

In Chrome,

the content of you add script dynamically will be running after the other contents are loaded.

Upvotes: 1

Related Questions