0

I have a simple page:

<!DOCTYPE html>
<html>
<head>
  <script>
    func = function(message) {
       alert(message);
    }
  </script>
</head>
<body>
  <h1> Visible content </h1>
</body>
</html>

and a script which is in separate file -- let's say -- test.js:

func("It should block the page.");

When I simply add this script to head by typing:

<script src="test.js"></script>

Alert shows before the content is visible which is fine to me.
However when I add the script dynamically:

<script>
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', 'test.js');
  document.getElementsByTagName('head')[0].appendChild(script);
</script>

Alert shows after the content.

Why does that happen? Shouldn't the browser wait untill the script finishes (including adding and loading a new one)? Is it possible to block the body content with dynamically added script?

PGJ
  • 126
  • 4
  • your dom (Document Object Model) isn't ready. Your code is executed before the elements on the page rendered. You have to use dom ready event, for example in jquery we use `$(document).ready(..code..);` – Dvir Oct 14 '13 at 22:08

2 Answers2

1

It happens because of asynchronous loading. Have a look at the article: http://css-tricks.com/thinking-async/

It depends what do you mean by blocking. You can load the page with the content block hidden: <div style="display:none;"></div> and show it after the page is loaded.

Here's jQuery way:

$(function () {
    // do stuff after DOM has loaded
});  

Have a look at this answer for more: javascript domready?

Community
  • 1
  • 1
Pavel
  • 542
  • 5
  • 11
  • I've already figured out such solution, hoped there is some other way. Anyway thanks for explaining asynchronous loading ;) – PGJ Oct 15 '13 at 07:03
-1

Wrap it in document.ready:

$(document).ready(function () {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', 'test.js');
  document.getElementsByTagName('head')[0].appendChild(script);
});
mayabelle
  • 9,804
  • 9
  • 36
  • 59