[javascript] Can I run javascript before the whole page is loaded?

I want to run a bit of javascript before the whole page has loaded. Is this possible? Or does the code start to execute on </html>?

This question is related to javascript html

The answer is


You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.