1

Say I have a script called makeFields.js which includes the method

function makeDateControls() {

    document.write(/* ... */);

}

In my HTML, I link to that script in the head, like so:

<head>
<script type="text/javascript" src="makeFields.js"></script>
</head>

Then in my HTML, I have an inline script outside the head:

<div>
<script>
    makeDateControls();
</script>
</div>

The question is: can I depend on the browser to wait for makeFields.js to finish downloading before it tries to call makeDateControls()? Does it matter whether I put the makeFields.js script tag in the head or in the body? Does the behavior depend on the presence of document.write()?

Although it seems like it wouldn't work, we haven't had any problems with this method as far as I can tell. Keep in mind however that I did not create this framework - I'm new on my team so change isn't easy.

Chris Middleton
  • 4,734
  • 1
  • 25
  • 54
  • 1
    The browsers process the HTML from top to bottom. Unless you explicitly specify that the script should be loaded *after* the rest of the document was processed, it will be loaded and evaluated right where it is located in the document. – Felix Kling Sep 19 '14 at 17:03
  • @Cerbrus Apart from being about script loading, my question and the question you linked have nothing in common. That question is asking how to run code after the body loads. Mine is about code that runs while the html is being generated (with document.write). – Chris Middleton Sep 19 '14 at 17:08
  • @AmadeusDrZaius: You're right, the close vote was incorrect. Re-opened. Any way, you _really_ shouldn't use `document.write()`. You'll have no idea where in the document the string is added. – Cerbrus Sep 19 '14 at 17:10
  • @Cerbrus The `document.write()` is contained in a function in an external script, but the function is called from an inline script. The question then is what effect this interaction has on the (a)synchrony of the page load. It seems to work, but I want to know how and/or if it's just a coincidence. – Chris Middleton Sep 19 '14 at 17:13
  • I don't see anything asynchronous here. What makes you think that having `document.write` would behave differently than not having it? – Felix Kling Sep 19 '14 at 17:27
  • At parsing time the result of [`document.write`](https://html.spec.whatwg.org/multipage/webappapis.html#document.write%28%29) is placed immediately after the script tag under execution, in your case after the `script` tag in the `body`. – Teemu Sep 19 '14 at 17:29
  • @Felix - Isn't the external script loaded asynchronously? – Chris Middleton Sep 19 '14 at 17:35
  • 1
    *"Scripts without async or defer attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page."* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script. That's the reason why things like ` ` works. That's the standard way of composing scripts. – Felix Kling Sep 19 '14 at 17:36

0 Answers0