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.

8
  • 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. Commented Sep 19, 2014 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). Commented Sep 19, 2014 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. Commented Sep 19, 2014 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. Commented Sep 19, 2014 at 17:13
  • 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." developer.mozilla.org/en-US/docs/Web/HTML/Element/script. That's the reason why things like <script src="jquery.js"></script> <script>$('div')...</script> works. That's the standard way of composing scripts. Commented Sep 19, 2014 at 17:36

0

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.