0

I have two scripts, which are included in the HTML body. In the first script I'm initializing a JS-Object which is referenced in the second script tag.

<body>
  ...
  <script type="text/javascript" src="http://url/script.js"></script>
  <script type="text/javascript">
     obj.a = 1000;
     obj.do();
  </script>
</body>

What is happening, if loading time of the first script (via HTTP) is slow? How is the execution order of the JS in the body?

4
  • See also the script async property. Commented Dec 10, 2012 at 18:12
  • @apsillers I don't think that's possible to use here if the inline script is referencing the external script... Commented Dec 10, 2012 at 18:14
  • @Ian True enough -- maybe you could cobble together a load listener for the external script, but it would be a nightmare for cross-browser compatibility. Otherwise, async is only useful if the linked script is the primary active script (i.e., not a library) or if the linked script fires a custom event announcing that it is ready, which most libraries don't do. Commented Dec 10, 2012 at 18:19
  • @apsillers Exactly, great explanation. That's why I'm weary of using async unless I design everything to work that way :) Commented Dec 10, 2012 at 18:31

1 Answer 1

2

<script> tags within page source are executed synchronously together with the page load.

The browser will not parse or render any HTML after the <script> tag until the script finishes downloading and executing.

This is why it's better to move all <script> tags to the bottom of the page, so that the HTML is rendered first.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. Another option is to wrap the second bit of js code in window.addEventListener('load', function() { ... your code here ... }); This way your inline script is executed only after everything's loaded.
@psema4 That doesn't help at all, since the first JS file still is blocking the HTML being rendered...
The question was about execution order of JS, not the blocking of HTML rendering. Using the eventListener ensures that the inline js would run at a specific time. (er, event)
the problem is, that sometime - for some reasons I cannot explain - the "obj" object which should be initialized in "url/script.js" is undefined (without any other errors). So if I get the comments right, this should not be happening, because the script.js is processed before the "obj.a = 1000;" instruction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.