Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  193] [ 5]  / answers: 1 / hits: 29441  / 13 Years ago, tue, february 21, 2012, 12:00:00

I've noticed some scripts seem to be called before others on a certain page, I was wondering, what is the specific order for scripts to load? In-page before referenced .js scripts? Are they run in order from first <script> mentioned to last in page, or Is this browser-dependent? How can one make sure that a specific script is first to run in a page?


More From » hoisting

 Answers
21

I've noticed some scripts seem to be called before others on a certain
page. I was wondering, what is the specific order for scripts to load?




This is set by W3C in their language specifications. For the HTML 4.01 Specification, for instance, it's defined in Section 18.2.4 Dynamic modification of documents, item 1.




In-page before referenced .js scripts?




See above. No, inline and linked scripts are handled identically.




Are they run in order from first mentioned to last in page,
or is this browser-dependent?




The specifications call for them to be run sequentially from top to bottom. You'll have to find a browser that implements the language according to specification. I can't think of any right now that handle SCRIPT tags differently, but I'm sure that is possible.



Another thing to consider is the definition of run. That may sound like semantic parsing, but it's not. JavaScript, like any programming language, is itself designed to behave according to standards. JavaScript is specified in the ECMA-262 5.1 Edition / June 2011 standard to evaluate from left-to-right in Section 7 Lexical Conventions. (Line endings are treated as the left-most character of the next line.) This document also provides conventions for the order in which statements and other operations are evaluated, such as WHILE or FOR statements.




How can one make sure that a specific script is first to run in a page?




(1) Put it at the top, and (2) choose a browser that implements the language specification.



However, I feel there may be something more behind this question. If you're trying to stop unexpected code from executing, you'll have to block it until the ONLOAD event handler registers that the page is complete. (Simply enclose your operations in a function or surround them with an IF to check for a boolean flag, i.e. isLoaded being set true by ONLOAD.) Then, when the ONLOAD event handler fires off, you can kick off operations on your own schedule without having to worry about things like uninstantiated DOM objects.


[#87308] Monday, February 20, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;