17

Is there a way to execute jQuery code before the DOM is ready ?

asked Sep 26, 2012 at 9:08
3
  • 2
    Yes. But parts of it that interact with the DOM won't work. Commented Sep 26, 2012 at 9:09
  • 2
    Yes there is, but given that jQuery is primarily intended to amend the DOM, why would you want to? Commented Sep 26, 2012 at 9:10
  • see:: stackoverflow.com/questions/4124765/… Commented Sep 26, 2012 at 9:11

2 Answers 2

20

jQuery is just Javascript, so the question is really "Is it possible to run JavaScript before the DOM is ready" and with that I'm guessing you mean the document and not DOM.

If we can agree that the question is "Is it possible to run JavaScript before the document is ready". Then the answer is yes. The JavaScript will be executed when encountered.

That's why you almost always see either $(function(){...})or $(document).ready(function(){...}) because most jQuery code requires the document to be ready but the code attaching the event handler is certainly executed before the document is ready (otherwise it wouldn't be able to handle the document ready event).

Usually you should place your Javascript includes at the bottom of your HTML but if you want it executed earlier you can simply place it earlier in the document e.g. in the header.

<html>
 <head>
 ...
 <script>
 //place your code to be executed early here
 </script>
 </head>
...
</html>
answered Sep 26, 2012 at 9:22
Sign up to request clarification or add additional context in comments.

Comments

4

If you include jQuery in the head of your document, and then write your code in another script tag in the head, it will run before the DOM is ready:

<head>
 <script src="jquery.js"></script>
 <script>
 // Do some stuff before the DOM is ready
 </script>
</head>
<body>
 <!-- Browser hasn't got this far, so no elements will be available -->
</body>

However, obviously you won't be able to interact with any DOM elements, since they won't exist yet.


Having said that, there is a technique you can use in modern browsers that can allow you to interact with DOM elements as they are inserted into the page (while the browser is rendering it). It relies upon CSS animation events. I've written a simple library (Progressive.js) to make this easier to handle.

answered Sep 26, 2012 at 9:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.