Make sure a Javascript script is first to run?

NoBugs picture NoBugs · Feb 22, 2012 · Viewed 23k times · Source

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?

Answer

jfriend00 picture jfriend00 · Feb 22, 2012

As long as no scripts are dynamically loaded or marked as async or defer, scripts are run or evaluated in the order encountered in the page. So, the first scripts encountered run first.

An externally referenced script file that must be loaded will cause all further javascript execution to wait until that externally referenced file is loaded and parsed and runs.

So, the evaluation order of normal (non-async, non-defer) javascript is 100% determinate as the order it is encountered in the page.