Kai
Kai

Reputation: 2073

If inline JavaScript code will be executed before document load event?

I have a page with <form> tag. Inside a form there is a lot of html plus some inline JavaScript at the very end of the <form> tag.
I listen to document load event. Can I be 100% sure, that when document load will be fired, all this inline JavaScript code has been already executed?
Example of markup:

<body>
  <form>
    --html controls---
    <script type="text/javascript">
      --some code to run here--
    </script>
  </form>
</body> 

My thoughts that answer is yes, inline JavaScript will be executed before document load, but I want to find evidence.

edit

live demo
Document load fires only when all html controls loaded and JavaScript (inline or with src attribute)loaded and interpreted. Am I correct with this statement?

Upvotes: 1

Views: 1276

Answers (3)

ted
ted

Reputation: 4975

I think you have no guarantees If it is a slow javascript (emscripten) i think it is possible that the code is still beeing executed while the onload fires.

but i could not find clear documentation: https://developer.mozilla.org/en/DOM/window.onload http://msdn.microsoft.com/en-us/library/ie/cc197055%28v=vs.85%29.aspx

http://www.w3.org/TR/html4/html40.txt :

onload = script [CT] The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.

so I can't find guarantees, you can either test (with something heavy, e.g. a demo from here https://github.com/kripken/emscripten/wiki), hpe for the best, or build in a savequard of your on that checks weather your inline script completed

Upvotes: 0

Neil
Neil

Reputation: 55392

Inline script will execute immediately as soon as the script tag finishes parsing, so you won't be able to access the rest of the document yet. On the other hand, it allows you to write additional HTML at that point in the document.

Note that Firefox 3.5 had a bug whereby you could set the defer attribute on the inline script and it would not execute immediately. This non-standard behaviour was fixed in Firefox 3.6.

Upvotes: 1

Grace Huang
Grace Huang

Reputation: 5679

Unless you put the code you want to execute in the domready callback function, your inline javascript code will be executed immediately when you load the page (before the the domready).

Upvotes: 4

Related Questions