Are external scripts in the head of an HTML document guaranteed to execute before scripts contained within the body?
I'm trying to execute some inline javascript within an HTML page as early in page processing as possible that makes use of library functions in an external .js file.
While I've always seen that putting library scripts in the head, and client scripts in the body just seems to work, I can't find documentation anywhere that says that external scripts included within the head of a document are guaranteed to run before script located within the body of a document (except on the w3schools site, but they don't count as a reputable reference)
To illustrate, I'm wondering about the User-Agent behavior for HTML that looks like this:
<html>
<head>
<script type="text/javascript src="libraryModule.js"></script>
</head>
<body>
<script type="text/javascript">
// is this guaranteed to run after the external script?
// or is it possible this module that the external library
// adds to the global namespace won't be there yet?
var result = ModuleInExternalLibrary.DoLibraryThing();
</script>
</body>
</html>
Is this documented anywhere? I can't find anything in the W3C spec or any good post that sums up the behavior in this area of all the major browsers. Please provide a link.
Am I stuck having to wait until the onload event fires in order to guarantee that external script开发者_StackOverflow中文版s have executed?
JavaScript statements that appear between <script>
and </script>
tags are executed in order of appearance. So yes, it is guaranteed, unless you are doing something clever like deferred loading or something similar.
Execution of JavaScript Programs
精彩评论