Search code examples
javascripthtmldynamicblocking

Why doesn't dynamically added script block the rest of the page from loading


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?


Solution

  • 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?