if i have multiple script tags in my page like:
<script src="js/jquery-1.7.min.js" type="text/javascript"></script>
<script src="js/jquery.jplayer.min.js" type="text/javascript"></script>
<script src="js/globals.js" type="text/javascript"></script>
<script src="js/sound.js" type="text/javascript"></script>
can i rely on the fact that code from the previous ones is already available when the latter ones are loaded?
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
The browser loads them in parallel and it is free to run them in whatever order it wants. There is no predictable order among multiple async things.
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
External JavaScript JavaScript files have the file extension .js.
They may be loaded (via the network) in parallel, but they are evaluated in sequence.
So yes, you can rely on the order.
Short: Yes:
Without specifying defer
or async
properties within the script tag, the spec says, that a browser has to sequentially (sync) load those files.
In other words, a plain script tag which a browser finds needs to get
While a "modern" browser probably still trys to optimize that process, those steps need to be applied (at least, process-like). That is the reason why you should place script tags without further specification always at the bottom of your <body>
tag. Even the DOM render process stops while loading/executing scripts.
To avoid that, you can specify a defer
or async
(HTML5 only) property in those script tags, like
<script defer src="/foo/bar.js"></script>
that tells the browser it is a script that meant to be executed after the document has been parsed.
See https://developer.mozilla.org/En/HTML/Element/Script
In general, scripts are downloaded sequentially (see this page):
Because JavaScript code can alter the content and layout of a web page, the browser delays rendering any content that follows a script tag until that script has been downloaded, parsed and executed. However, more importantly for round-trip times, many browsers block the downloading of resources [such as stylesheets, images, and other scripts] referenced in the document after scripts until those scripts are downloaded and executed.
They are loaded in parallel but they run only once every file have been loaded. So the answer is yes, you can rely on the fact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With